0

假设我有两个数组,如下所示:

$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 中

4

2 回答 2

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)

于 2012-04-09T13:59:29.387 回答
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);
于 2012-04-09T13:58:43.617 回答