phparraysmultidimensional-array

Combine columnar values in each row of a 2d array to form dynamically keyed elements


I have this array:

$params = [
    ['name'  => 'xxx', 'value' => 'yyy'],
    ['name'  => 'uuu', 'value' => 'vvv']
];

and I want to achieve this:

$params = [
    ['xxx' => 'yyy'],
    ['uuu' => 'vvv']
];

I can do it this way:

foreach ($params as &$param) {
    $param[$param['name']] = $param['value'];
    unset($param['name']);
    unset($param['value']);
    unset($param);
}

But I am wondering if this could be done on more elegant way?


Solution

  • This calls for an array mapping of values:

    $params = array_map(function ($i) { return [$i['name'] => $i['value']]; }, $params);