假设我有两个如下所示的数组:
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
我想得到这样的结果:
$arr4 = array("first", "second", "third", "fourth", "fifth", "sixth", "seventh","eighth", "ninth","tenth", "eleventh" );
怎么做?用PHP
答案 0 :(得分:2)
你想要的是展平和组合阵列。在array_values的PHP手册中,http://www.php.net/manual/en/function.array-values.php#104184
的注释中有一个很好的扁平化函数以下是代码:
/**
* 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;
}
只需在array($arr2, $arr3)
上运行。
答案 1 :(得分:0)
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);