Thursday, 30 August 2018

How to change the multidimensional php array into a simple associative array with values ​​as keys?

So I want to turn a multidimensional array into a simple associative array that uses every second value as a key and every third value as a value to that key.
The initial array looks like this:
Array
(
[0] => Array
    (
        [id] => 1
        [name] => Adam
        [value] => 150
    ),

[1] => Array
    (
        [id] => 2
        [name] => Bob
        [value] => 120
    ),

[2] => Array
    (
        [id] => 3
        [name] => Charlie
        [value] => 175
    )

)

I want to turn it into a simple associative array that looks like this:
Array
(
Adam => 150,
Bob => 120,
Charlie => 175
)

I tried (and failed with) something like this:
$initialArray;
$arrayPrepped = array();
    foreach ($initialArray as $part) {
        foreach ($part as $name => $value) {
            if ($name == 'name') {
                $key = $value;
            } elseif ($name == 'value') {
                $finalvalue = $value;
            }
            $finalpart = array($key => $finalvalue);
        }
        array_merge($initialArray, $finalpart);
    }


What about this one-liner!
print_r(array_column($initialArray, 'value', 'name'));

Read up on array_column.

0 comments:

Post a Comment