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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵