在php中chunk所有相同值的数组

时间:2017-09-27 09:41:48

标签: php

我有多维数组, 我必须将所有具有相同ID的子数组分组。 我尝试使用chunk但它无法正常工作

Array
(
    [0] => Array
        (
            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )
    [1] => Array
        (

            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )
    [2] => Array
        (
            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )

    [3] => Array
        (
            [ID] => A11496
            [CID] => 000020
            [msgtype] => Periodic Report

        )
    )   

期望输出如下面的数组

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )

            [1] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report

                )

            [2] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )
        )
    [1] => Array
        (   
            [0] => Array
                (
                    [ID] => A11496
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )

            [1] => Array
                (
                    [ID] => A11496
                    [CID] => 000020
                    [msgtype] => Periodic Report

                )
        )       
    )   

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php
    $oldArray = array();
    $newArray = array();

    foreach($oldArray as $item){
        if(isset($newArray[$item['ID']])){
            array_push($newArray[$item['ID']], $item);
        }else{
            $newArray[$item['ID']] = $item;
        }
    }
?>