
根据键值合并 php 多维数组
在 php 中,我们经常需要对多维数组进行合并,比如将具有相同键值的元素合并为一个键。下面是一个具体的例子:
问题:
给定以下 json 数组:
立即学习“PHP免费学习笔记(深入)”;
[
{
"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中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号