简体   繁体   中英

PHP: key->value from two array elements

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...

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.

If you have array_column available you can do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM