[英]PHP Convert multidimensional array in one dimensional array of arrays
I have array of 15 elements and each element contains 1000 arrays. 我有15个元素的数组,每个元素包含1000个数组。 How can I convert all this arrays in one simple dimensional array?
如何将所有这些数组转换为一个简单的维数组? I need to get this inner arrays and convert this in one dimensional array of arrays.
我需要获取此内部数组并将其转换为数组的一维数组。
Array
(
[0] => Array
(
[0] => Array[0..999]
[1] => Array[0..999]
[2] => Array[0..999]
)
[1] => Array
(
[0] => Array[0..999]///items are also arrays
[1] => Array[0..999]
)
[2] => Array
(
[0] => Array[0..999]
[1] => Array[0..999]
[2] => Array[0..999]
)
....
It needs to look like this: 它需要看起来像这样:
Array(
[0] => Array
[0]=>value
[1]=>value
[2]=>value
[1] => Array
[0]=>value
[1]=>value
[2]=>value
)
array_merge()
will merge multiple arrays, but you have an unspecified number in the main array. array_merge()
将合并多个数组,但是主数组中的数字未指定。 So use the array as the parameters for call_user_func_array()
with array_merge()
as the callback: 因此,使用数组作为
call_user_func_array()
的参数,并以array_merge()
作为回调:
$result = call_user_func_array('array_merge', $array);
Create an empty 'main' array and merge the 15 arrays into it 创建一个空的“主”数组,并将15个数组合并到其中
$main_array = [];
foreach($big_array as $value)
{
$main_array = array_merge($main_array,$value);
}
eg: 例如:
$main_array = [];
foreach([[1],[2],[3,4,5,6,7]] as $value)
{
$main_array = array_merge($main_array,$value);
}
print_r($main_array);
//output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
A recursive function, one that calls itself, could do the trick, eg 一个递归函数(可以自己调用)可以解决问题,例如
<?php
$currentArray = [*your multi-dim array*];
$targetArray = [];
$level = 0;
$targetArray = flattenArray($currentArray, $targetArray, $level);
function flattenArray($currentArray, $targetArray, $level){
foreach($currentArray as $value){
if(is_array($value) AND $level < 1){
$targetArray = flattenArray($value, $targetArray, $level + 1);
}else{
$targetArray[] = array(print_r($value, TRUE));
}
}
return $targetArray;
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.