Help with array_walk

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Help with array_walk

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

For flattening an array, a recursive function is better suited. :)

However, where are $a2Element, and $key defined?
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post 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
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post 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>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply