Mandy
Mandy

Reputation: 1103

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

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.

Upvotes: 7

Views: 3635

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31739

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'];
}

Upvotes: 9

Related Questions