-3
function transformArray($array, $key)
{
  $transformed = [];
  foreach ($array as $k => $value) {
   $transformed[] = $value[$key]
 }
 return $transformed;
}

$array = [
0 => [
'key' => 1,
'key2' => 2
]
];

transformArray($array, 'key2');

Often I need function to build array from multidimesions array, for that I'm write function like in example, some frameworks have own function to do this, maybe for this solution exist shortest way with standart PHP functions ?

Wizard
  • 10,985
  • 38
  • 91
  • 165

1 Answers1

2

Take a look to array_column function (supported since PHP 5.5).
It returns the values from a single column in the input multi-dimensional array.
Example from official documentation:

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);

// output:
        Array
    (
        [0] => John
        [1] => Sally
        [2] => Jane
        [3] => Peter
    )

http://php.net/manual/ru/function.array-column.php

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105