PHP按日期将数据从mysql排序到数组


PHP sort data from mysql to array by date

我想为用户显示过去30天(包括今天)的统计数据。但在我的数据库中,只有特定日期的统计数据,如果用户做了任何操作的话。如果没有,日期就不在那里,而这一天的值只需要为0。这是我目前的方法,数据是从数据库中接收的,但没有正确插入。

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt2 = $conn->prepare("SELECT * FROM all_stats WHERE user_id = :user_id ORDER BY date DESC LIMIT 30"); 
$stmt2->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt2->execute();
$rows2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
// Create array with dates of the last 29 days and today.
for($i=29;$i>=0;$i--){
    $dates[$i] = date("Y-m-d", strtotime("-".$i." day" ));
}
// Check what rows are available
$y=0;
foreach ($rows2 as $row) {
   $daterow[$y] = $row['date'];
   $us[$y] = $row['US'];
   $ca[$y] = $row['CA'];
   $au[$y] = $row['AU'];
   $gb[$y] = $row['GB'];
   $de[$y] = $row['DE'];
   $y++;                       
}
$size = count($us);
for ($i = 0; $i<=29;$i++){
    if ( strtotime( $daterow[$i]) != strtotime($dates[$i]) ){
        $daily[$i] = 0;
    } else {
        $daily[$i] = $us[$i];
    }
}

测试数据为:今天数据可用,昨天为空,前天数据可用。

输出,仅插入今天的数据(在[0])错误

Array ( [0] => 333 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 [14] => 0 [15] => 0 [16] => 0 [17] => 0 [18] => 0 [19] => 0 [20] => 0 [21] => 0 [22] => 0 [23] => 0 [24] => 0 [25] => 0 [26] => 0 [27] => 0 [28] => 0 [29] => 0 )

问题在于,在执行最后一个循环时,在$daterow$dates数组中都使用了相同的索引。这不是您想要的,因为匹配的值将不在同一索引中。

我建议使用array_search:

// Create array with dates of the last 29 days and today.
for($i=29;$i>=0;$i--){
    $dates[$i] = date("Y-m-d", strtotime("-".$i." day" ));
    // at the same time initialise $daily
    $daily[$i] = 0;
}
// Check what rows are available
$y=0;
foreach ($rows2 as $row) {
    $daterow[$y] = $row['date'];
    //... etc..
    // Now search the $dates for the date we just read from the DB:
    $i = array_search($row['date'], $dates);
    if ($i !== false) {
        // There was a match, so add up what we have for US:
        $daily[$i] += $row['US'];
    }
    $y++;
}

上面假设$row〔'date’〕的日期格式与$dates中的元素一样,即YYYY-MM-DD。如果不是这样,你可能需要做一些调整,但这个想法应该有效。