我想我的标题已经把你迷住了。但这正是我真正需要的:
我有一个像这样的数组:
array(
'0' => array( 'the','data','i'),
'1' => array( 'need', 'is', 'this'),
'2' => array( 'complete', 'sentence')
);
我想成为:
array(
'the','data','i','need','is','this','complete','sentence'
);
随机:
- 子数组元素的元素个数。
- 子数组元素的个数。
由于您提出的问题似乎不是递归平坦化的一般问题,因此可能值得在这里给出简单的解决方案作为答案,尽管其他SO问题涉及一般情况。
你所需要的是
call_user_func_array("array_merge", $a);
查看完整脚本:
<?php
$a = array(
array( 'the',' data', 'i' ),
array( 'need', 'is', 'this' ),
array( 'complete', 'sentence' )
);
echo var_dump($a);
echo "<br/><br/><br/>";
$b = call_user_func_array("array_merge", $a);
echo var_dump($b);
?>
这会通过附加数组来构建结果,并且效率很低。您可以查看SplFixedArray
,它允许您预先分配空间。然后遍历原始数组中的组成数组并加载结果。这是一篇讨论SplFixedArray
的博客文章,包括计时结果:http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/
这里是一个详细的版本:
<?php
$a = array(
array( 'the','data','i'),
array( 'need', 'is', 'this'),
array( 'complete', 'sentence')
);
$size = 0;
foreach ($a as $subarray) {
$size += count($subarray);
}
$result = new SplFixedArray($size);
# If you do not have SPL, just use $result = Array(); and write to a high index first (probably)
$i = 0;
foreach ($a as $subarray) {
foreach ($subarray as $value) {
$result[$i++] = $value;
}
}
echo var_dump($result);
?>