如何使用数组值作为无钥匙圈? [英] How to use array values as keys without loops?

查看:90
本文介绍了如何使用数组值作为无钥匙圈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

循环播放时费时,大家都知道。这正是东西我试图避免的,即使它是在小范围内。每一点帮助。好吧,如果这是未设置的课程:)

Looping is time consuming, we all know that. That's exactly something I'm trying to avoid, even though it's on a small scale. Every bit helps. Well, if it's unset of course :)

我有一个数组:

array(3) {
    '0' => array(2) {
        'id'   => 1234,
        'name' => 'blablabla',
    },
    '1' => array(2) {
        'id'   => 1235,
        'name' => 'ababkjkj',
    },
    '2' => array(2) {
        'id'   => 1236,
        'name' => 'xyzxyzxyz',
    },
}

我想要做的就是这个数组转换如下:

What I'm trying to do is to convert this array as follows:

array(3) {
    '1234' => 'blablabla',
    '1235' => 'asdkjrker',
    '1236' => 'xyzxyzxyz',
}

我想这AINT一个很难的事情可以做,但我的心是捣毁现在,我想不出任何东西,除了循环完成这件事。

I guess this aint a hard thing to do but my mind is busted right now and I can't think of anything except for looping to get this done.

推荐答案

只需使用 array_combine 沿 array_column

array_combine(array_column($array,'id'), array_column($array,'name'));

或者你可以简单地使用 array_walk 如果您对PHP< 5.5为

Or you can simply use array_walk if you have PHP < 5.5 as

$result = array();
array_walk($array, function($v)use(&$result) {
    $result[$v['id']] = $v['name']; 
});

编辑:

有关谁拥有未来的用户PHP> 5.5可以简单地使用 array_column

For future user who has PHP > 5.5 can simply use array_column as

array_column($array,'name','id');

小提琴(array_walk)

这篇关于如何使用数组值作为无钥匙圈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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