I have an array like this
$users = array(
[0] => array('Id' => 3, 'Name' => 'Bob'),
[1] => array('Id' => 8, 'Name' => 'Alice'),
)
and I want to pull the Ids ‘up’ one level so that the final array is:
$usersById = array(
[3] => array('Id' => 3, 'Name' => 'Bob'),
[8] => array('Id' => 8, 'Name' => 'Alice'),
)
The Id values are unique.
Is there a native PHP way to do this? The code I’m currently using is:
$usersById = array();
foreach ($users as $key => $value)
{
$usersById[$value['Id']] = $value;
}
This works, but is not terribly elegant.
Modern answer (requires PHP 5.5)
The new function
array_columnis very versatile and one of the things it can do is exactly this type of reindexing:Original answer (for earlier PHP versions)
You need to fetch the ids from the sub-arrays with
array_map, then create a new array witharray_combine:The code above requires PHP >= 5.3 for the anonymous function syntax, but you can also do the same (albeit it will look a bit uglier) with
create_functionwhich only requires PHP >= 4.0.1:See it in action.