PHP array is reduced to a sub-array element

I have an array like this

$users = array(
    [0] => array('Id' => 3, 'Name' => 'Bob'),
    [1] => array('Id' => 8, 'Name' => 'Alice'),
)

and I want to bring the identifiers up one level to the last array:

$usersById = array(
    [3] => array('Id' => 3, 'Name' => 'Bob'),
    [8] => array('Id' => 8, 'Name' => 'Alice'),
)

Id values ​​are unique.

Is there a native PHP way to do this? The code I use is:

$usersById = array();
foreach ($users as $key => $value)
{
    $usersById[$value['Id']] = $value;
}

It works, but not very elegant. Thank!

+5
source share
5 answers

Modern answer (requires PHP 5.5)

The new feature is array_columnvery versatile, and one of the things it can do is just this type of reindexing:

// second parameter is null means we 're just going to reindex the input
$usersById = array_column($users, null, 'Id');

Original answer (for earlier versions of PHP)

You need to get the identifiers from subarrays with array_map, and then create a new array with array_combine:

$ids = array_map(function($user) { return $user['Id']; }, $users);
$users = array_combine($ids, $users);

PHP >= 5.3 , ( ) create_function, PHP >= 4.0.1:

$ids = array_map(create_function('$user', 'return $user["Id"];'), $users);
$users = array_combine($ids, $users);

.

+15

array_reduce(), :

$usersById = array_reduce($users, function ($reduced, $current) {
    $reduced[$current['Id']] = $current;
    return $reduced;
});

, foreach.

+9

, foreach . , -:

$keyed = array();
foreach($users as $w) $keyed[$w['Id']] = $w;

, foreach . , , :

$users = function($key) use ($users)
{
    foreach($users as $v) $keys[] = $v[$key];
    return array_combine($keys, $users);
};
$users = $users('Id');

callback , . , .

+2

array_walk:

$usersById = array();
array_walk($users, function($val) use (&$usersById) {
    $usersById[$val['Id']] = $val;
});
+1
 $usersById = array_combine(array_keys($users), array_values($users));
-2

All Articles