0

I think I blew you away by the title. But here's what I exactly need:

I have an array like this:

array(
 '0' => array( 'the','data','i'),
 '1' => array( 'need', 'is', 'this'),
 '2' => array( 'complete', 'sentence')
);

which I want to become:

array(
 'the','data','i','need','is','this','complete','sentence'
);

What's random:

  1. The number of elements in a child array element.
  2. The number of child array elements.
kapeels
  • 1,692
  • 4
  • 30
  • 52
  • 1
    Probable dupe: http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php – Ray Toal Aug 21 '11 at 05:50
  • The solution there, would it good to process over 10k elements(total)? – kapeels Aug 21 '11 at 05:53
  • Good question, @KPL. The solutions there do consider the general case in which the arrays are nested to an arbitrary depth. If you are interested only in merging at the top level, then you can write something more efficient without using recursion. – Ray Toal Aug 21 '11 at 06:01

1 Answers1

2

Since the problem you posed does not appear to be the general one of recursive flattening, it is probably worth giving the simple solution as an answer here, even though other SO questions address the general case.

All you need is

call_user_func_array("array_merge", $a);

To see it in a complete script:

<?php
$a = array(
    array( 'the',' data', 'i' ),
    array( 'need', 'is', 'this' ),
    array( 'complete', 'sentence' )
);

echo var_dump($a);
echo "<br/><br/><br/>";
$b = call_user_func_array("array_merge", $a);
echo var_dump($b);
?>

This builds up the result by appending arrays and can be inefficient. You can check out SplFixedArray which allows you to preallocate space. Then traverse the constituent arrays in your original array and load up the result. Here is a blog post that discusses SplFixedArray and includes timing results: http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/

Here is a verbose version:

<?php
$a = array(
    array( 'the','data','i'),
    array( 'need', 'is', 'this'),
    array( 'complete', 'sentence')
);

$size = 0;
foreach ($a as $subarray) {
    $size += count($subarray);
}

$result = new SplFixedArray($size);
# If you do not have SPL, just use $result = Array(); and write to a high index first (probably)

$i = 0;
foreach ($a as $subarray) {
    foreach ($subarray as $value) {
        $result[$i++] = $value;
    }
}

echo var_dump($result);
?>
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • But, does `array_values` not serve the same purpose? – kapeels Aug 21 '11 at 06:18
  • The [`array_values`](http://php.net/manual/en/function.array-values.php) function just produces a numerically indexed array, ignoring keys. I don't see how it helps for flattening, but that doesn't mean it cannot be used. – Ray Toal Aug 21 '11 at 06:30