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条)

报告相同问题?

悬赏问题

  • ¥15 excel 上下按钮 显示行
  • ¥20 搭建三相栅极电路后高侧浮动地VS存在电容特性
  • ¥20 云卓h12pro 数传问题
  • ¥20 请问有人知道怎么用工艺库里面的sdb文件通过virtuoso导出来library里面每个cell的symbol吗?
  • ¥20 海思 nnie 编译 报错
  • ¥50 决策面并仿真,要求有仿真结果图
  • ¥15 关于路由器的路由协议配置
  • ¥15 springboot接入微信支付SDK
  • ¥50 大区域的遥感影像匹配 怎么做啊
  • ¥15 求解答:pytorch跑yolov8神经网络受挫