PHP Multidimensional Array Rearranging

ぃ、小莉子 提交于 2019-12-25 18:44:34

问题


Sir,

I am confused what should be exact title of this issues. Below is my problem

I have a multidimensional array like below

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
        )

)

Now, I want to make unique date beside time should be into another array. I want it as below...

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
                )

        )

)

Thanks in advance..

Regards,

Anwar


回答1:


Something of that fashion should do the trick...

Its nowhere near the fastest way to do so but it should get you going and it is pretty easy to read/understand

// 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];
}


来源:https://stackoverflow.com/questions/47441091/php-multidimensional-array-rearranging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!