du27271 2018-06-14 18:26
浏览 612
已采纳

在php中合并重复的数组值

I have a multidimensional array like:

Array
(
    [0] => Array
        (
            [division] => Mymensingh
            [A] => 1
        )    
    [1] => Array
        (
            [division] => Dhaka
            [A] => 5
        )
    [2] => Array
        (
            [division] => Mymensingh
            [B] => 2
            [C] => 5
        )
)

Need to find the same value of division index and merge them in one array. May be there is PHP functions to do this. I could not figure it out. Now from this array I want the output as:

Array
    (
        [0] => Array
            (
                [division] => Mymensingh
                [A] => 1
                [B] => 2
                [C] => 5
            )    
        [1] => Array
            (
                [division] => Dhaka
                [A] => 5
            )
    )

Index of sub arrays can be different and also can be different numbers of.

  • 写回答

2条回答 默认 最新

  • dongshan0202405 2018-06-14 18:40
    关注

    I think it's relatively simple to just iterate through the array and continuously merge the entries separated by "division":

    function mergeByDiscriminator($input, $discriminator = 'division') {
        $result = [];
    
        foreach ($input as $array) {
            $key = $array[$discriminator];
            $result[$key] = array_merge(
                array_key_exists($key, $result) ? $result[$key] : [],
                $array
            );
        }
    
        return array_values($result);
    }
    
    $result = mergeByDiscriminator($input); // $input is your array
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?