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');
2
  • 2
    Have you made any attempt? Should be pretty simple. Commented Jan 8, 2015 at 14:56
  • possible duplicate of PHP - unset in a multidimensional array Commented Jan 8, 2015 at 14:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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.