How to change this array into keys and values

Tags: , ,



I have this array…

[
 [
  [
    "name" => "Initials"
    "value" => "ROR"
  ],
  [
    "name" => "Awards"
    "value" => "Swimming"
  ],
],
[
  [
    "name" => "Initials"
    "value" => "NAL"
  ],
  [
    "name" => "Awards"
    "value" => "Cycling"
  ],
 ]
]

What’s the best way for me to change this array so I can save it like this…

[
  [
    "Initials" => "ROR"
    "Awards" => "Swimming"
  ],
  [
    "Initials" => "NAL"
    "Awards" => "Cycling"
  ],
]

I’ve started doing something like looping through them and this… but this gives me one array element per new array.

foreach($array as $rows) {
    foreach($rows as $field) {
        $values[] = [$field['name'] => $field['value']];
    }
}

Answer

You can use array_column() to index the inner array, specifying the column to use as the value and the one to index it by…

$values = [];

foreach($array as $rows) {
    $values[] = array_column($rows, "value", "name");
}
print_r($values);

gives…

Array
(
    [0] => Array
        (
            [Initials] => ROR
            [Awards] => Swimming
        )

    [1] => Array
        (
            [Initials] => NAL
            [Awards] => Cycling
        )

)


Source: stackoverflow