我想转换
$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
向
$array = [1,2,3,4,5,6,7,8,9,10];
我可以用
$array = [];
foreach($array_of_arrays as $one_array):
$array = array_merge($array,$one_array);
endforeach;
但是我有很长的数组,是否存在任何没有foreach循环的函数(方法)
答案 0 :(得分:4)
使用call_user_func_array
功能:
$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
$result = call_user_func_array("array_merge", $array_of_arrays);
print_r($result);
输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
答案 1 :(得分:3)
您可以将array_merge
与call_user_func_array
:
$res = call_user_func_array('array_merge', $array_of_arrays);
var_dump($res);
array(10) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
[3] =>
int(4)
[4] =>
int(5)
[5] =>
int(6)
[6] =>
int(7)
[7] =>
int(8)
[8] =>
int(9)
[9] =>
int(10)
}
答案 2 :(得分:3)
//使用array_merge和call_user_func_array
$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
$oneDimensionalArray = call_user_func_array('array_merge', $array_of_arrays);
print_r( $oneDimensionalArray);
//输出将是:Array([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] = > 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10)
//了解有关call_user_func_array()PHP call_user_func with class and arguments
的更多信息