1

I have an multidimensional array like this:

Position 0: {id=5, name=john}
Position 1: {id=7, name=frank}
Position 2: {id=9, name=tina}

What I'm trying to do is: Change the Position Key (0,1,2) to id value for each one!

Position 5: {id=5, name=john}
Position 7: {id=7, name=frank}
Position 9: {id=9, name=tina}

I tried to use "array_flip" according to PHP Doc. But I did not succeed! But I just found reference for unidimensional arrays. Like this:

<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);    
print_r($flipped);
?>

Any idea? Thanks.

1 Answer 1

2

A simple oneliner:

$new_array = array_combine(
    array_column($your_array, 'id'),    // these are keys
    $your_array                         // these are values
);
Sign up to request clarification or add additional context in comments.

2 Comments

I like that you expanded the one-liner to multiple lines to include the explanation of the arguments.
I would make it: $new_array = array_combine( array_column($your_array, 'id'), array_column($your_array, 'name')); making the array flat since the ID is the key anyways.

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.