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

Link to comment
Share on other sites

<?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))))));

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.