我有这个代码:
$data = array();
$groupedData = array();
while ($row = mysqli_fetch_array($result)) {
$date = DateTime::createFromFormat("Y-m-d", $row["date"]);
$groupedData[$date->format("Y")][$date->format("m")][$date->format("d")] = $row;
$data[] = $date;
}
我在这里想做的是从数据库中获取所有日期并按年/月/日对它们进行排序
问题是,对于 2018 年 9 月 2 日,我在 mysql 中有两行,它们不会添加到我的数组中,因为“日”将是重复的。
而不是这个:
Array
(
[2018] => Array
(
[September] => Array
(
[02] => text 1
[02] => text 2
[12] => text 3
[31] => text 4
)
)
)
我明白了:(当然,由于数组的工作原理,第二个“day 2”被省略了。)
Array
(
[2018] => Array
(
[September] => Array
(
[02] => text 1
[12] => text 3
[31] => text 4
)
)
)
如何解决此问题并拥有唯一的数组键,以便可以回显 9 月 2 日的两个日期?
最佳答案
我会在另一个级别进入数组。在这种情况下,所有日期都包含一个具有多个值的数组。
像这样:
$data = array();
$groupedData = array();
while ($row = mysqli_fetch_array($result)) {
$date = DateTime::createFromFormat("Y-m-d", $row["date"]);
$groupedData[$date->format("Y")][$date->format("m")][$date->format("d")][] = $row;
$data[] = $date;
}
数组示例:
Array
(
[2018] => Array
(
[September] => Array
(
[02] => Array
(
[0] => text 1
[1] => text 2
)
[12] => Array
(
[0] => text 3
)
[31] => Array
(
[0] => text 4
)
)
)
)
关于mysql - 在mysql中使用while时出现重复的数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51381928/