I have arrays structured like below:
array(2) {
["uid"]=>
string(2) "39"
["name"]=>
string(18) "Manoj Kumar Sharma"
}
array(2) {
["uid"]=>
string(2) "47"
["name"]=>
string(11) "S kK Mishra"
}
I want these array should be like this below:
array(4) {
[39]=>
string(18) "Manoj Kumar Sharma"
[47]=>
string(11) "S kK Mishra"
}
How can i achieve this ? Please help me.
Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);
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.
Traversing the Associative Array Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.
Updated
You can try this with array_column() -
$new = array_column($arr, 'name', 'uid');
Demo
Note: array_column()
not available for PHP < 5.5
If you are using lower versions of PHP the use a loop.
$new = array();
foreach($your_array as $array) {
$new[$array['uid']] = $array['name'];
}
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