Page 1 of 1

Help with array_walk

Posted: Wed Feb 01, 2006 7:45 am
by tores
Hi,

I'm trying to make a 2-dimensional array 1-dimensional with the following code:

Code: Select all

/* Make array one-dimentional */
$a2D = array(array(1,2,3,4), array(5,6,7,8));
$a1D = array();

array_walk($a2D, create_function('$a2Element, $key, &$a1', '$a1 = array_merge($a1, $a2Element); print_r($a1);'), $a1D);

print_r($a1D);
But it doesn't seem that passing $a1D by reference helps because the output is:

Code: Select all

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
)
Array
(
)
$a1D is still empty after the array walk. Is there a way to make this work?

regards tores.

Posted: Wed Feb 01, 2006 8:12 am
by Jenk
For flattening an array, a recursive function is better suited. :)

However, where are $a2Element, and $key defined?

Posted: Wed Feb 01, 2006 8:26 am
by tores
$a2Element is a value in $a2D, and $key is corresponding key / index. (Check out http://no.php.net/manual/en/function.array-walk.php)

How would you do this recursively?

tores

Posted: Wed Feb 01, 2006 9:00 am
by raghavan20
This could be an alternative..

Code: Select all

<pre>
<?php
$array1 = array(array(1,2,3,4), array(5,6,7,8)); 
$array2 = array();
foreach($array1 as $arrayItem){
	$array2 = array_merge($array2, $arrayItem);
}
print_r($array2);
?>

</pre>

Posted: Wed Feb 01, 2006 9:08 am
by feyd
untested

Code: Select all

<?php

function flatten($array) {
  $return = array();
  $array = array_values($array);
  foreach($array as $value) {
    if(is_array($value)) {
      $return += flatten($value);
    } else {
      $return[] = $value;
    }
  }
}

?>
however, I wouldn't do it recursively as they can and will eat memory. It is quite possible to do it without recursion, just takes a bit more time to write and is slightly more complex.