PHP array_reduce 初始参数为数组

Mat*_*s17 5 php arrays reduce dictionary

我有这个初始数组:

[
    0 => ['id' => 5, 'value' => 50],
    1 => ['id' => 6, 'value' => 60],
    2 => ['id' => 7, 'value' => 70],
]
Run Code Online (Sandbox Code Playgroud)

并想将其转换为:

[
    5 => ['value' => 50],
    6 => ['value' => 60],
    7 => ['value' => 70],
]
Run Code Online (Sandbox Code Playgroud)

起初,我尝试使用map,但它无法修改数组键,所以我认为reduce可以解决问题,因为它将数组减少为单个值,在本例中为数组。所以我尝试:

array_reduce(
    $array,
    function($carry, $item) {
        return $carry[$item['id']] = $item['value'];
    },
    []
);
Run Code Online (Sandbox Code Playgroud)

但它返回这个错误Cannot use a scalar value as an array。我究竟做错了什么?无法array_reduce接收数组作为初始值吗?

Ale*_*dar 6

array_reduce没有工作,因为你没有carry从回调函数返回累加器数组(在你的情况下)。

array_reduce(
    $array,
    function($carry, $item) {
        $carry[$item['id']] = $item['value'];
        return $carry; // this is the only line I added :)
    },
    []
);
Run Code Online (Sandbox Code Playgroud)

我在寻找使用方法时想到了这个问题array_reduce,所以我觉得我应该写这篇评论。我希望这对未来的读者有所帮助。:)


Mur*_*san 1

正如Mark Baker它所做的那样。我也用foreach循环做了。

$arr = array(
            array('id' => 5, 'value' => 50),
            array('id' => 6, 'value' => 60),
            array('id' => 7, 'value' => 70)
        );

$result = array();
$result = array_column($arr, 'value', 'id'); 
array_walk($result, function(&$value) { $value = ['value' => $value]; });


//I did this using foreach loop, But the OP need it through array function.
//foreach($arr as $key => $value){
//    $result[$value['id']] = array('value' => $value['value']);
//}

echo '<pre>';
print_r($result);
Run Code Online (Sandbox Code Playgroud)

结果:

Array
(
    [5] => Array
        (
            [value] => 50
        )

    [6] => Array
        (
            [value] => 60
        )

    [7] => Array
        (
            [value] => 70
        )

)
Run Code Online (Sandbox Code Playgroud)