How can a simple array be flattened without loops?

I would like to turn a simple multidimensional array into an even simpler array.

Turn this:

Array
(
    [0] => Array
        (
            [id] => 123
        )
    [1] => Array
        (
            [id] => 456
        )
    ...
    [999] => Array
        (
            [id] => 789
        )
)

      

Into an array like this:

Array
(
    [0] =>  123
    [1] => 456
    ...
    [999] => 789
)

      

I would like to do without a loop using foreach

. Is this possible in PHP?

This is how I can solve it with a loop foreach

:

$newArr = array();
foreach ($arr as $a) {
    $newArr[] = $a['id'];
}
$arr = $newArr;

      

I would like to do this without loops. You can help?

+3


source to share


2 answers


You can do map

it:

$arr = array_map(function($element) {
    return $element['id'];
}, $arr);

      

Since it's array_map

possible to loop internally, you can do it for real without a loop:



$arr = array_reduce($arr, function($arr, $element) {
    $arr[] = $element['id'];
    return $arr;
});

      

But there is no reason for no cycle. There is no real performance gain, and your code's readability will probably decrease.

+3


source


I admire your desire for something that comes close to functional programming and implicit looping, but PHP is the wrong language for you. It does not express itself naturally in a functional style.

The function reset

returns the first element in the array, so you can map this function over the array:

array_map('reset', $array)

      

However, in PHP the fastest method is a simple loop for

(not foreach

, for

). Here are a bunch of different flattening techniques. Only functions containing for

and foreach

do an explicit loop and are included for comparison.

function flatten_for($arr) {
    $c = count($arr);
    $newarr = array();
    for ($i = 0; $i < $c; $i++) {
        $newarr[] = $arr[$i][0];
    }
    return $newarr;
}


function flatten_for_inplace($arr) {
    $c = count($arr);
    for ($i = 0; $i < $c; $i++) {
        $arr[$i] = $arr[$i][0];
    }
}


function flatten_foreach($arr) {
    $newarr = array();
    foreach ($arr as $value) {
        $newarr[] = $value[0];
    }
    return $newarr;
}

function flatten_foreach_inplace($arr) {
    foreach ($arr as $k => $v) {
        $arr[$k] = $v[0];
    }
}

function flatten_foreach_inplace_ref($arr) {
    foreach ($arr as &$value) {
        $value = $value[0];
    }
}

function flatten_map($arr) {
    return array_map('reset', $arr);
}

function flatten_walk($arr) {
    array_walk($arr, function(&$v, $k){$v = $v[0];});
}

function visitor($v, $k, &$a) {
    return $a[] = $v;
}

function flatten_walk_recursive($arr) {
    $newarr = array();
    array_walk_recursive($arr, 'visitor', $newarr);
    return $newarr;
}

function reducer($result, $item) {
    return $item[0];
}

function flatten_reduce($arr) {
    return array_reduce($arr, 'reducer', array());
}

function flatten_merge($arr) {
    return call_user_func_array('array_merge_recursive', $arr);
}

      

Here is the sync code:



function buildarray($length) {
    return array_map(function($e){return array($e);}, range(0, $length));
}

function timeit($callable, $argfactory, $iterations) {
    $start = microtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        call_user_func($callable, call_user_func($argfactory));
    }
    return microtime(true) - $start;
}

function time_callbacks($callbacks, $argfactory, $iterations) {
    $times = array();
    foreach ($callbacks as $callback) {
        $times[$callback] = timeit($callback, $argfactory, $iterations);
    }
    return $times;
}

function argfactory() {
    return buildarray(1000);
}

$flatteners = array(
    'flatten_for', 'flatten_for_inplace', 'flatten_foreach',
    'flatten_foreach_inplace', 'flatten_foreach_inplace_ref',
    'flatten_map', 'flatten_walk', 'flatten_walk_recursive',
    'flatten_reduce', 'flatten_merge',
);

$results = time_callbacks($flatteners, 'argfactory', 1000);

var_export($results);

      

On an old MacBook Pro (Core 2 Duo, 2.66GHz, 8GB, PHP 5.3.15 with Suhosin-Patch) I get the following results:

array (
  'flatten_for' => 12.793387174606,
  'flatten_for_inplace' => 14.093497991562,
  'flatten_foreach' => 16.71691608429,
  'flatten_foreach_inplace' => 16.964510917664,
  'flatten_foreach_inplace_ref' => 16.618073940277,
  'flatten_map' => 24.578175067902,
  'flatten_walk' => 22.884744882584,
  'flatten_walk_recursive' => 31.647840976715,
  'flatten_reduce' => 17.748590946198,
  'flatten_merge' => 20.691106081009,
)

      

The difference between methods for

and is foreach

less on longer arrays.

Surprisingly (to me, anyway) flatten_merge

still slower than a simple loop for

. I expected to array_merge_recursive

be at least as fast, if not faster, as it basically transfers all the work to a C function!

+5


source







All Articles