Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make array first value as key for the second value as value in php array

Tags:

arrays

php

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.

like image 444
Mandy Avatar asked Feb 17 '16 08:02

Mandy


People also ask

How do I change the value of a key in an array?

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.

How do you get the first key of an array?

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);

What is array_keys () used for in PHP?

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.

What is key in associative array in PHP?

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.


1 Answers

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'];
}
like image 130
Sougata Bose Avatar answered Sep 25 '22 10:09

Sougata Bose