array_map 2d array to 1d associative array

坚强是说给别人听的谎言 提交于 2019-12-13 12:09:29

问题


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"
}

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);

回答1:


If you are using PHP5.5 then you can use the array_column function - documentation

$names = array_column($records, 'Name', 'ID');

Otherwise, an array_map solution is probably as good as you can get:

$names = array_combine(array_map(function($value) {
     return $value['ID'];
}, $records), array_map(function($value) {
     return $value['Name'];
}, $records));

Here's the array_combine docs



来源:https://stackoverflow.com/questions/25300402/array-map-2d-array-to-1d-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!