我有这个初始数组:
[
0 => ['id' => 5, 'value' => 50],
1 => ['id' => 6, 'value' => 60],
2 => ['id' => 7, 'value' => 70],
]
并想将其转换为:
[
5 => ['value' => 50],
6 => ['value' => 60],
7 => ['value' => 70],
]
起初,我尝试使用 map
,但它不能修改数组键,所以我认为 reduce
可以解决问题,因为它 reduces 数组为单个值,在本例中为数组。所以我尝试了:
array_reduce(
$array,
function($carry, $item) {
return $carry[$item['id']] = $item['value'];
},
[]
);
但它返回此错误 Cannot use a scalar value as an array
。我究竟做错了什么? array_reduce
不能接收数组作为初始值吗?
最佳答案
您的 array_reduce
没有工作,因为您没有从回调函数返回累加器数组(在您的情况下为 carry
)。
array_reduce(
$array,
function($carry, $item) {
$carry[$item['id']] = $item['value'];
return $carry; // this is the only line I added :)
},
[]
);
我在寻找使用 array_reduce
的方法时遇到了这个问题,所以我觉得我应该写这篇评论。我希望这对 future 的读者有所帮助。 :)
关于PHP array_reduce 初始参数为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37075840/