0

I have an existing array in PHP like so (when i use print_r):

Array (
    [0] => Array(
        [value] => 188
        [label] => Lucy
    )  
    [1] => Array (
        [value] => 189
        [label] => Jessica
    ) 
    [2] => Array (
        [value] => 192
        [label] => Lisa
    ) 
    [3] => Array (
        [value] => 167
        [label] => Carol
    ) 
    // and so on...
) 

From this array i need to manipulate or create a new array like so:

Array (
    [Lucy] => 188
    [Jessica] => 189
    [Lisa] => 192
    [Carol] => 167
) 

What's the best way of doing so?

I need the names to become the keys so i can then sort alphabetically like so:

uksort($array, 'strnatcasecmp');
odd_duck
  • 3,941
  • 7
  • 43
  • 85
  • 2
    Have you made any attempt? Should be pretty simple. – Patrick Q Jan 08 '15 at 14:56
  • possible duplicate of [PHP - unset in a multidimensional array](http://stackoverflow.com/questions/7260468/php-unset-in-a-multidimensional-array) – johnny Jan 08 '15 at 14:58

3 Answers3

6

IMHO the best and easiest option is this:

$newArray = [];
foreach ($array as $var) {
   $newArray[$var['label']] = $var['value'];
}

Note: if doesn't work because of [] then change first line to classic version: $newArray = array(); as it's the same.

Forien
  • 2,712
  • 2
  • 13
  • 30
6

PHP 5.5 has a nice new array_column() function that will do exactly that for you. I think you want something like this:

$result = array_column($array, 'value', 'label');
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
0

You could use array_reduce as well, like so:

$new_array = array_reduce($old_array, function($new_array, $item) {
    $new_array[$item['label']] = $item['value'];
    return $new_array;
}, array());

In simple scenarios this is arguably overkill. In applications where a lot of array transformation is going on, the second argument of array_reduce can be factored out and replaced depending on context.

lampyridae
  • 949
  • 1
  • 8
  • 21