Jump to content

Recursive function for multidimensional arrayunpack


MrXHellboy

Recommended Posts

Hi all,

 

Ok, simple question...

 

just imagine a multidimensional array,

array(array(1,2,3,array(4,5,6, array(7,8,9))));

 

how to build a recursive function that will unpack all the arrays into 1 array.

 

Somehow, none of my tries has worked out properly :(

 

Cheers

<?php
function array_unpack($array)
{
$new_array = array();
foreach($array as $key=>$val)
	if(is_array($val)) 
		$new_array = array_merge($new_array, array_unpack($val));
	else
		$new_array[] = $val;
return $new_array;
}
var_dump(array_unpack(array(array(1,2,3,array(4,5,6, array(7,8,9))))));

?>

Thx! Any other possibility for this ? I want to use the keys as well, and add a prefix to the key accordingly.... Array_merge does not support key options in this way as far as i know.

 

So:

array(array('Key' => 1,2,3,array(4,5,6, array('Key' => 7,8,9))))

 

the second key 'Key' must get a prefix.... is not really possible with array_merge ?!

 

Cheers

this?

function array_unpack($array, $str="")
{
$new_array = array();
foreach($array as $key=>$val)
{
	if(is_array($val)) 
		$new_array = array_merge($new_array, array_unpack($val, $str.$key."."));
	else if(is_int($key))
			$new_array[] = $val;
	else
			$new_array[$str.$key] = $val;
}
return $new_array;
}

And 1 thing more.

 

Why doesn't need

$new_array = array_merge($new_array, array_unpack($val, $str.$key."."));

 

brackets and

$new_array[] = $val;

 

does ?

 

It seems like you are overwriting this variable each time, but it doesnt... So what the big deal there

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.