Mysql查询:
select id, ad_click, contact_submit, MONTH(datetime) as months, YEAR(datetime) years from wpxc_leaderboard_counters order by datetime
它以这种方式显示结果:
Array (
[0] => Array (
[0] => stdClass Object (
[id] => 2 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01
)
[1] => stdClass Object (
[id] => 3 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01
)
[2] => stdClass Object (
[id] => 4 [ad_click] => 1 [contact_submit] => 0 [datetime] => 2019-11-01
)
[3] => stdClass Object (
[id] => 5 [ad_click] => 0 [contact_submit] => 1 [datetime] => 2019-11-01
)
[4] => stdClass Object (
[id] => 1 [ad_click] => 3 [contact_submit] => 2 [datetime] => 2019-12-06
)
)
)
但想以这种方式显示:
Array (
[0] => Array (
[11] => stdClass Object (
[id] => 2 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01
[id] => 3 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01
[id] => 4 [ad_click] => 1 [contact_submit] => 0 [datetime] => 2019-11-01
[id] => 5 [ad_click] => 0 [contact_submit] => 1 [datetime] => 2019-11-01
)
[12] => stdClass Object (
[id] => 1 [ad_click] => 3 [contact_submit] => 2 [datetime] => 2019-12-06
)
)
)
希望这可以通过修改数组来实现,因为我使用了不同的方法并且花费了很多时间,但仍未实现。
答案 0 :(得分:3)
在获取查询结果时,可以将日期的子字符串用作数组键。
while ($row = $query->fetch_object()) {
$result[substr($row->datetime, 5, 2)][] = $row;
}
您显示的数组与查询不完全匹配。如果您已经在查询中选择MONTH,则无需使用substr
。您可以使用
$result[$row->months][] = $row;
我还建议您考虑按年份和月份进行分组,以用于将来的排序目的,但是由于您的查询是按日期时间排序的,因此目前这可能无关紧要。这取决于您打算如何使用分组数据,但是如果将Year作为密钥的一部分,则可以确保组将始终正确排序。