Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array conversion using array_map/array_walk functions

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!

like image 223
Grizerg Avatar asked Apr 11 '26 06:04

Grizerg


1 Answers

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.

like image 87
deceze Avatar answered Apr 13 '26 21:04

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!