2

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;
});
Peter
  • 8,776
  • 6
  • 62
  • 95

3 Answers3

5

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);
Titi
  • 1,126
  • 1
  • 10
  • 18
1

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'];
}
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
0

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100