[英]array_map 2d array to 1d associative array
I have a 2d Array (returned from PDO MySQL DB) that is of the form 我有一个2d数组(从PDO MySQL DB返回)的形式
{
[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"
}
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. 我知道我可以循环并以这种方式创建数组,但我觉得这可能没有像花哨的array_map那样有效。
Basically I want something like... 基本上我想要像......
array_map(
function ($value) {
return $value['ID']=>$value['Name'];
}, $ResultArray);
If you are using PHP5.5 then you can use the array_column
function - documentation 如果您使用的是PHP5.5,那么您可以使用array_column
函数 - 文档
$names = array_column($records, 'Name', 'ID');
Otherwise, an array_map
solution is probably as good as you can get: 否则, array_map
解决方案可能就像你能得到的一样好:
$names = array_combine(array_map(function($value) {
return $value['ID'];
}, $records), array_map(function($value) {
return $value['Name'];
}, $records));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.