I have the following multidimensional array:
$userList = array(
0 => array('id' => 1000, 'first_name' => 'John', 'last_name' => 'Smith'),
1 => array('id' => 1001, 'first_name' => 'Sam', 'last_name' => 'Johnson'),
);
I want to convert it to the array like:
$userData = array(
1000 => 'John Smith',
1001 => 'Sam Johnson',
);
It's quite obvious for me how to implement this using foreach loop, but I wonder if it's possible to do this with PHP array functions like array_map or array_walk. Please use PHP 5.3 for the callback function. Thank you!
Since those functions only work on the array values, getting them to set the key in the new array is somewhat awkward. One way to do it is:
$arr = array_combine(
array_map(function ($i) { return $i['id']; }, $arr),
array_map(function ($i) { return "$i[first_name] $i[last_name]"; }, $arr)
);
This is a case where a foreach is much more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With