mysql - 在mysql中使用while时出现重复的数组键

标签 mysql arrays

我有这个代码:

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

相关文章:

mysql - MYSQL 临时表中的多次插入

java - 如何创建 2D char 数组的 2D 数组?

php - 如何在 PHP 中通过类共享 MySQL 连接?

php - 从数据库中选择值的下拉列表 php

javascript - 无法在函数内部编辑数组

c - 将两个字符数组的值相加

c - 将值从文件存储到 C 中的结构数组

Java:将字符串数组项解析为 int、double 或 string

mysql - 发送数据库行列表(例如要在 Nodejs 中查看的对象)

返回整数(32 位 int)的 PHP 哈希函数