Reputation: 47
Suppose I have two arrays like the following:
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
And I want a result like this:
$arr4 = array("first", "second", "third", "fourth", "fifth", "sixth", "seventh","eighth", "ninth","tenth", "eleventh" );
How to do that? in PHP
Upvotes: 0
Views: 128
Reputation: 91942
What you want to is flatten and combine the arrays. There's a nice function for flattening in the comments in the PHP manual of array_values, http://www.php.net/manual/en/function.array-values.php#104184
Here's the code:
/**
* Flattens an array, or returns FALSE on fail.
*/
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Just run this on array($arr2, $arr3)
.
Upvotes: 2
Reputation: 65274
function flatten($ar,&$res) {
if (is_array($ar))
foreach ($ar as $e) flatten($e,$res);
else
$res[]=$ar;
}
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
$arr4=array();
flatten($arr2,$arr4);
flatten($arr3,$arr4);
Upvotes: 0