2015-12-12 42 views
0

我想显示过去30天(包括今天)的用户的统计信息。 但在我的数据库中只有特定日期的统计信息,如果用户做了任何操作。如果没有日期,那么这一天的值只需要为0.这是我目前的方法,数据是从数据库中接收的,但它没有被正确插入。PHP按日期排序数据从mysql到数组

$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) 

回答

2

的问题是,你在这两个$ daterow$日期使用同一指数数组,同时通过你的最后一个循环。这不是你想要的,因为匹配值不会在相同的索引处。

我建议要做到这一点,利用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++; 
} 

以上假设$行[“日期”]有格式化一样的$日期,即元素的日期YYYY-MM-DD。如果情况并非如此,你可能需要做一些调整,但这个想法应该起作用。

+0

非常感谢这么多,我只是复制+粘贴你的代码在文件中,它的工作:) – Veeza

+0

不客气。 – trincot