本文介绍了array_map 2d数组到1d关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维数组(从PDO MySQL DB返回),其格式为
I have a 2d Array (returned from PDO MySQL DB) that is of the form
{
[0] => {
"ID" => 1,
"Name" => "Name1"
},
[1] => {
"ID" => 2,
"Name" => "Name2"
},
[2] => {
"ID" => 3,
"Name" => "Name3"
}
}
是否有一种优雅/有效的解决方案将其转换为
Is there an elegant/efficient solution to transform it to
{
[1] => "Name1",
[2] => "Name2",
[3] => "Name3"
}
我知道我可以遍历并以这种方式创建数组,但是我觉得这可能不如花哨的array_map效率高。
I know I could loop through and create the array that way, but i feel like that may be less efficient than something like a fancy array_map.
基本上我想要的东西...
Basically I want something like...
array_map(
function ($value) {
return $value['ID']=>$value['Name'];
}, $ResultArray);
推荐答案
如果您使用的是PHP5.5,则可以使用 array_column
函数-
If you are using PHP5.5 then you can use the array_column
function - documentation
$names = array_column($records, 'Name', 'ID');
否则, array_map
解决方案可能是
$names = array_combine(array_map(function($value) {
return $value['ID'];
}, $records), array_map(function($value) {
return $value['Name'];
}, $records));
这篇关于array_map 2d数组到1d关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!