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)
非常感谢这么多,我只是复制+粘贴你的代码在文件中,它的工作:) – Veeza
不客气。 – trincot