如何将子值添加到新数组?

I have an array with every containing value being another array with one value. I was looking for a way to flatten the array and succeeded but somehow I am having this feeling that it can be done better. Is this the best way or can it still be improved?

<?php

$array = array(
    '1' => array('id' => '123'),
    '2' => array('id' => '22'),
    '3' => array('id' => '133'),
    '4' => array('id' => '143'),
    '5' => array('id' => '153'),
);

array_walk_recursive($array, function($v, $k) use (&$result) {
    $result[] = $v;
});

You can achieve that using the array_map function:

$func = function($value) {
    return $value['id'];
};
$array2 = array_map($func, $array);

Or if you want to keep it in one line do:

 $array2 = array_map(function($value) { return $value['id']; }, $array);

This will return the array flattened and keeps your initial keys:

    array(5) {
      [1]=>
          string(3) "123"
      [2]=>
          string(2) "22"
      [3]=>
          string(3) "133"
      [4]=>
          string(3) "143"
      [5]=>
          string(3) "153"
    }

If you don't want to keep the keys, then call the following at the end:

$array2 = array_values($array2);

If the depth won't ever change a foreach loop would likely be faster. That anonymous function has some overhead to it and it really shows the longer your array gets.

If the depth is variable as well, however, then this is the fastest way to traverse and flatten.

This is what I would do. Its cleaner:

$array = array(
    '1' => array('id' => '123'),
    '2' => array('id' => '22'),
    '3' => array('id' => '133'),
    '4' => array('id' => '143'),
    '5' => array('id' => '153'),
);
foreach($array as $key => $arr){
    $result[] = $arr['id'];
}

You can use array_map() passing null as the first argument while unpacking the passed array with the splat operator and grab the first element of the result:

$result = array_map(null, ...$array)[0];

Another option would be to use array_column() which creates an array from a single column of a given multidimensional array - feed it your array and column key, e.g.:

$result = array_column($array, 'id');

Output for either:

print_r($result);

Array
(
    [0] => 123
    [1] => 22
    [2] => 133
    [3] => 143
    [4] => 153
)