odd_duck
odd_duck

Reputation: 4111

PHP - Get array within array and store/manipulate

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

Upvotes: 0

Views: 67

Answers (3)

lampyridae
lampyridae

Reputation: 991

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.

Upvotes: 0

Alex Howansky
Alex Howansky

Reputation: 53563

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

Upvotes: 6

Forien
Forien

Reputation: 2763

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.

Upvotes: 6

Related Questions