1

Basically, I have an array where each element is a key/value pair of elements, like this:

[myArray] => Array
        [0] => Array
                [id] => 121
                [name] => Value1
        [1] => Array
                [id] => 125
                [name] => Value2
        [2] => Array
                [id] => 129
                [name] => Value3
                ....

And I want to convert this to:

[myArray] => Array        
        [121] => Value1
        [125] => Value2
        [129] => Value3
        ....

so the 'id' element becomes the key, and the 'name' element becomes the value. Does PHP have something built in (or is there a clever trick) to do this? I'd like to avoid the obvious foreach() loop if there's something cleaner available...

1
  • 3
    I don't know if there is a built-in function to handle this task, but even if there is, it's definitely using some sort of loop structure to accomplish the task. A simple foreach loop should more than suffice. Is that a problem in your implementation? Commented Jul 17, 2013 at 1:04

2 Answers 2

5

PHP 5.5 has an array_column() function which can do this for you, if you're lucky enough to be running that already. The developer who submitted it also has a forwards-compatible version you can download for earlier versions of PHP.

However, it's pretty easy to roll your own, or just use a foreach loop for the particular case you need.

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

1 Comment

Unfortunately we're running in a 5.3 environment and that's not getting changed any time soon. Thanks though, array_column() is EXACTLY what I needed =)
0

If you have array_column available you can do:

array_column($myArray, 'name', 'id')

I think the foreach is the much better option, though.

2 Comments

why the complicated combine? array_column($myArray, 'name','id') would suffice..
Ah. Wasn't aware of the index argument. Nice.

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.