PHP多维数组重排

时间:2017-11-22 17:54:32

标签: php arrays multidimensional-array

爵士

我很困惑这个问题的确切标题。以下是我的问题

我有一个多维数组,如下所示

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => 9 Am
        )

    [1] => Array
        (
            [0] => 2017-11-02
            [1] => 07 Pm
        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => 11 Pm
        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => 03 Pm
        )

    [4] => Array
        (
            [0] => 2017-11-01
            [1] => 11 Am
        )

    [5] => Array
        (
            [0] => 2017-11-02
            [1] => 05 Pm
        )

)

现在,我希望在时间旁边创建唯一的日期应该是另一个数组。 我想要它如下......

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => Array
                (
                    [0] => 9 Am
                    [1] => 11 Am
                )

        )

    [1] => Array
        (
            [0] => 2017-11-02
            [1] => Array
                (
                    [0] => 07 Pm
                    [1] => 05 Pm
                )

        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => Array
                (
                    [0] => 11 Pm
                )

        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => Array
                (
                    [0] => 03 Pm
                )

        )

)

提前致谢..

此致

安华

1 个答案:

答案 0 :(得分:1)

那种时尚应该可以解决问题...

它远不是最快的方式,但它应该让你去,它很容易阅读/理解

// putting the times in a new array where the date is the key

$byDate = [];
foreach ($firstArray as [$date, $time]) {
    $byDate[$date][] = $time;
}


// going thru it again to have it the way you needed it

$newArray = [];
foreach ($byDate as $date => $times) {
    $newArray[] = [$date, $times];
}