1, "Name" => ...">

Array_map 2d array to 1d associative array

I have a 2d Array (returned from PDO MySQL DB) which has the form

{
  [0] => {
    "ID" => 1,
    "Name" => "Name1"
  },
  [1] => {
    "ID" => 2,
    "Name" => "Name2"
  },
 [2] => {
    "ID" => 3,
    "Name" => "Name3"
  }
}

      

Is there an elegant / efficient solution to convert it to

{
  [1] => "Name1",
  [2] => "Name2",
  [3] => "Name3"
}

      

I know I could iterate over and create an array this way, but I feel like it might be less efficient than something like fancy array_map.

Basically, I want something like ...

array_map(
  function ($value) { 
    return $value['ID']=>$value['Name']; 
  }, $ResultArray);

      

+3


source to share


1 answer


If you are using PHP5.5 you can use function array_column

- documentation

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

      

Otherwise, the solution array_map

is probably as good as you can:



$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

+9


source







All Articles