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.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
PHP | array_flip() Function This built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string.
The new function array_column
is very versatile and one of the things it can do is exactly this type of reindexing:
// second parameter is null means we 're just going to reindex the input
$usersById = array_column($users, null, 'Id');
You need to fetch the ids from the sub-arrays with array_map
, then create a new array with array_combine
:
$ids = array_map(function($user) { return $user['Id']; }, $users);
$users = array_combine($ids, $users);
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_function
which only requires PHP >= 4.0.1:
$ids = array_map(create_function('$user', 'return $user["Id"];'), $users);
$users = array_combine($ids, $users);
See it in action.
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