如何使用数组值作为没有循环的键? [英] How to use array values as keys without loops?
问题描述
循环很耗时,我们都知道.这正是我试图避免的事情,即使它的规模很小.每一点都有帮助.好吧,当然如果它没有设置:)
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',
}
我想这不是一件很难的事情,但我现在脑子里一片空白,除了循环来完成这件事外,我想不出任何事情.
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
as
Simply use array_combine
along with the array_column
as
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
as
For future user who has PHP > 5.5 can simply use array_column
as
array_column($array,'name','id');
这篇关于如何使用数组值作为没有循环的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!