7

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.

6
  • 1
    just use a foreach, then assign it in another array using uid as the key and name as the value, you can just try Commented Feb 17, 2016 at 8:14
  • Above one is single multidimensional array or two different single- dimensional array? Commented Feb 17, 2016 at 8:15
  • 1
    @A-2-A, there is no difference, imho... Commented Feb 17, 2016 at 8:24
  • difference is there. you didn't get me. Commented Feb 17, 2016 at 8:29
  • @A-2-A, if it isn't multidimensional array but you need it to be that way - you can just make it multidimensional array. So, where is the difference, exactly? Commented Feb 17, 2016 at 9:04

1 Answer 1

9

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'];
}
Sign up to request clarification or add additional context in comments.

5 Comments

array_column accepts a third parameter, which would make this even easier. Read the documentation you link to again yourself.
@deceze Thanks. Never went through that. :)
thats working fine as i required. but i have one issue with my current query which i am executing. $results = db_query("SELECT DISTINCT u.uid as uid, u.name as name FROM users u WHERE u.uid IN (SELECT p.endpoints_entity_id as uid FROM field_data_endpoints p JOIN relation r ON r.rid = p.entity_id WHERE p.bundle = 'subuser' AND p.deleted = 0 AND p.delta = 0 AND r.uid = $user->uid)")->fetchAll(PDO::FETCH_ASSOC); This query creating duplicate array. How can i resolved this issue.
You can apply array_unique to the array. Can you add the actual array you are getting.
Googlers: heads up, if you simply need to re-index the array, set column_key (2nd argument) to null, and index_key to the value name that needs to become the key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.