How can I change my array sorting to like that

43 views Asked by At

This is my array which I get on my database:

Array (

 [0] => Array 
    ( 
        [ID] => 4 
        [USERNAME] => John
    ) 

[1] => Array 
    ( 
        [ID] => 7 
        [USERNAME] => Ted 
    ) 

)

But I want to like this:

Array 
( 
   [4] => John 
   [7] => Ted 
) 

I tried to do like I want by using array_merge, array_push etc. But I couldn't.

3

There are 3 answers

0
Bill Criswell On BEST ANSWER

I'd use a simple foreach.

$users = array();

foreach ($results as $user) {
  $users[$user['ID']] = $user['USERNAME'];
}
0
Barmar On

There's no built-in function for this, just write a simple loop:

$new_array = array();
foreach ($array as $e) {
    $new_array[$e['ID']] = $e['USERNAME'];
}
0
Mark Baker On

If you're using PHP >= 5.5 you can do this:

$newArray = array_combine(
    array_column($oldArray, 'ID'),
    array_column($oldArray, 'USERNAME')
);

EDIT

For earlier versions of PHP, a simple equivalent is

$newArray = array_combine(
    array_map(function($value) { return $value['ID']; }, $oldArray ),
    array_map(function($value) { return $value['USERNAME']; }, $oldArray )
);