5

I have this initial array:

[
    0 => ['id' => 5, 'value' => 50],
    1 => ['id' => 6, 'value' => 60],
    2 => ['id' => 7, 'value' => 70],
]

and want to convert it to:

[
    5 => ['value' => 50],
    6 => ['value' => 60],
    7 => ['value' => 70],
]

At first, I tried to use map, but it can't modify the array keys, so I thought reduce would solve the problem because it reduces the array to a single value, in this case, an array. So I tried:

array_reduce(
    $array,
    function($carry, $item) {
        return $carry[$item['id']] = $item['value'];
    },
    []
);

But it returns this error Cannot use a scalar value as an array. What am I doing wrong? Does array_reduce cannot receive an array as an initial value?

4
  • did you need to use array function or manual will be okey? Commented May 6, 2016 at 15:15
  • I'm trying to do it as functional as I can, I know a simple foreach would solve the problem. Commented May 6, 2016 at 15:16
  • 3
    Not really what array_reduced is supposed to do at all: $newArray = array_column($oldArray, 'value', 'id'); array_walk($newArray, function(&$value) { $value = ['value' => $value]; }); Demo Commented May 6, 2016 at 15:16
  • Oh, that works. If you post the answer I will gladly accept it Commented May 6, 2016 at 15:21

5 Answers 5

6

Your array_reduce didn't work because You weren't returning the accumulator array (carry in Your case) from the callback function.

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

I came to this question while looking for a way to use array_reduce, so I felt I should write this comment. I hope this will help future readers. :)

Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer I think. I was doing return $list[$client->ID] = $client->post_title; which didn't produce the correct array if I just put it on its own line and hten returned list it worked.
@ChristopherKarlsson thank You! I am glad this helped with Your issue :) However, I will let the author decide whether this will become the accepted answer. I think he already did, but it' never too late. Regards, Aleksandar
1

As Mark Bakerdid it. I also did with foreach loop.

$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);

Result:

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

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

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

)

Comments

1

Sometimes the best solutions are the simplest. Loop through your array and assign the id and value to a new array.

$new_array = array();    
foreach ($array as $key => $arr) {
    $new_array[$arr['id']] = array('value' => $arr['value']);
}

2 Comments

I know, i know, is just that I wanted to do it as functional as possible. But thanks anyway!
I totally get that. I think the issue would be with using array_map or array_walk is that you would have an issue converting the keys/indexes i.e. from 0 to 5. At least this way it's very little code for the results you need.
0

You can do it functionally. I suspect it's not actually more readable however.

array_combine(
    array_column($a, 'id'), 
    array_map(function($v) { return ['value' => $v['value']]; }, $a)
);

Or even...

array_map(
  function($v) { return ['value' => $v['value']]; }, 
  array_column($a, null, 'id')
)

Comments

0
array_reduce($ar, function ($acc, $item) {
        $acc[$item['id']] = [ 'value' => $item['value']]; 
        return $acc;
    }, [])

1 Comment

While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.