0

How can I make a multidimensional array like the first key becomes the root key and the second key becomes the value?

Is there any build in function for this, if yes then which one?

My Input array is:

Array
(
    [key1] => Array
        (
            [key] => key1
            [label] => value1
        )

    [key2] => Array
        (
            [key] => key2
            [label] => value2
        )

    [key3] => Array
        (
            [key] => key3
            [label] => value3
        )

    [key4] => Array
        (
            [key] => key4
            [label] => value4
        )

)

Expected Output:

Array (
    [key1] => value1

    [key2] => value2

    [key3] => value3

    [key4] => value4

)

I can do it with iterating the for loop on array, but just looking for any existing function(s)!

3 Answers 3

2

You can, indeed, do this without a loop with some native functions.

On top of my head:

$combined = array_combine( array_keys( $input ), array_column( $input, 'label' ) ); 

Or if you want to take key from the item:

$combined = array_column( $input, 'label', 'key' );
Sign up to request clarification or add additional context in comments.

2 Comments

Second one also worked for me, which one is better? for sure second option still want your thoughts...
It depends where you want keys to come from, to preserve keys from original array or to take some value from every item as a key to use. For your given example data these two should be the same (since keys of the array are the same as key values in items).
1

You can try out this combination of core array functions,

$input = array_combine(array_keys($input), array_column($input, 'label'));

array_combine — Creates an array by using one array for keys and another for its values
array_keys — Return all the keys or a subset of the keys of an array
array_column — Return the values from a single column in the input array

Comments

1

You can try array_reduce:

$array = // .. your array
$result = array_reduce($array, function($carry, $item){
    $carry[$item->key] = $item->value;
    return $carry;
},[]);

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.