PHP:键盘>由两个数组元素值 [英] PHP: key->value from two array elements

查看:140
本文介绍了PHP:键盘>由两个数组元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个数组,其中每个元素都是一个键/值对的元素,像这样的:

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

和我想将其转换为:

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

所以ID元素成为关键,而'名字'元素变成值。 PHP是否有一些内置的(或者是有一个很聪明的技巧)来做到这一点?我想,以避免明显的foreach()循环,如果有可用的清洁......事情

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有一个 array_column()功能它可以为你做这个,如果你足够幸运,运行已经。谁提交它还开发商有一个向前兼容的版本,你可以下载对之前版本的PHP。

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.

然而,这是pretty容易推出自己的,或者只是使用的foreach 循环您需要的特殊情况。

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

这篇关于PHP:键盘>由两个数组元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆