根据键值合并 php 多维数组
在 php 中,我们经常需要对多维数组进行合并,比如将具有相同键值的元素合并为一个键。下面是一个具体的例子:
问题:
给定以下 json 数组:
[ { "workid": "jp20221113", "in_stock": 10100 }, { "workid": "jp20221114", "in_stock": 5124 }, { "workid": "jp20221113", "out_stock": 10100 }]
如何根据 workid 键合并此数组,得到以下结果?
[ { "workid": "jp20221113", "in_stock": 10100, "out_stock": 10100 }, { "workid": "jp20221114", "in_stock": 5124 }]
回答:
我们可以使用 array_reduce 函数循环数组,并将 workid 作为键合并数组元素。
$data = json_decode(<<<json[ { "workid": "jp20221113", "in_stock": 10100 }, { "workid": "jp20221114", "in_stock": 5124 }, { "workid": "jp20221113", "out_stock": 10100 }]json , true);$result = array_reduce($data, function ($result, $current) { // 按照 workid 键合并 $target = array_merge($result[$current['workid']] ?? [], $current); $result[$current['workid']] = $target; return $result;}, []);$result = array_values($result);var_dump($result);// 易读版$result = [];foreach ($data as $item) { $result[$item['workid']] = array_merge($result[$item['workid']] ?? [], $item);}$result = array_values($result);var_dump($result);
输出:
array(2) { [0]=> array(3) { ["workID"]=> string(10) "JP20221113" ["in_stock"]=> int(10100) ["out_stock"]=> int(10100) } [1]=> array(2) { ["workID"]=> string(10) "JP20221114" ["in_stock"]=> int(5124) }}
如你所见,数组已成功按 workid 键合并。
以上就是PHP中如何根据键值合并多维数组?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » PHP中如何根据键值合并多维数组?