Peter Peter - 7 months ago 15
PHP Question

How to add subvalues to a new array?

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

Answer

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