php 数组按指定某些相同字段合并重组

瞌睡虫
  • 20

根据id和cateid相等的项进行合并重组(proid和sunnum)初始数据格式如下:

"list": [
            {
                "id": "01",
                "cateid": "12",
                "proid": "31",
                "sunnum": "200",
            },
            {
                "id": "01",
                "cateid": "12",
                "proid": "32",
                "sunnum": "10",
            },
            {
                "id": "02",
                "cateid": "13",
                "proid": "33",
                "sunnum": "2",
            },
            {
                "id": "03",
                "cateid": "14",
                "proid": "34",
                "sunnum": "12",
            }
        ]

最终效果类似:

"list": [
            {
                "id": "01",
                "cateid": "12",
                "proid": [
                    {
                        "proid":"31",
                    },
                    {
                        "proid":"32",
                    }
                ],
                "sunnum": "210",
            },
            {
                "id": "02",
                "cateid": "13",
                "proid": [
                    {
                        "proid":"33",
                    }
                ],
                "sunnum": "2",
            },
            {
                "id": "03",
                "cateid": "14",
                "proid": [
                    {
                        "proid":"34",
                    }
                ],
                "sunnum": "12",
            }
        ]
回复
阅读 456
2 个回答

最简单直接的方法,直接遍历重组

<?php

$arrs = [
    [
        "id"     => "01",
        "cateid" => "12",
        "proid"  => "31",
        "sunnum" => "200",
    ],
    [
        "id"     => "01",
        "cateid" => "12",
        "proid"  => "32",
        "sunnum" => "10",
    ],
    [
        "id"     => "02",
        "cateid" => "13",
        "proid"  => "33",
        "sunnum" => "2",
    ],
    [
        "id"     => "03",
        "cateid" => "14",
        "proid"  => "34",
        "sunnum" => "12",
    ],
];

$newArr = [];
foreach ($arrs as $arr) {
    if (isset($newArr[$arr['id'] . '-' . $arr['cateid']])) {
        $nowData                                   = $newArr[$arr['id'] . '-' . $arr['cateid']];
        $newArr[$arr['id'] . '-' . $arr['cateid']] = [
            'id'     => $arr['id'],
            'cateid' => $arr['cateid'],
            'proid'  => array_merge($nowData['proid'], [['proid' => $arr['proid']]]),
            'sunnum' => $nowData['sunnum'] + $arr['sunnum'],
        ];
    } else {
        $newArr[$arr['id'] . '-' . $arr['cateid']] = [
            'id'     => $arr['id'],
            'cateid' => $arr['cateid'],
            'proid'  => [['proid' => $arr['proid']]],
            'sunnum' => $arr['sunnum'],
        ];
    }
}

var_dump(array_values($newArr));
宣传栏