我正在尝试将多维数组排序到一个排序的一维数组,在该数组中,同一级别的值被合并在一起,并由它的父级之间的键交替排序。
首先从这个数组开始:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 60
[1] => 68
[2] => 71
[3] => 72
)
)
[1] => Array
(
[0] => Array
(
[0] => 61
[1] => 62
[2] => 64
)
[1] => Array
(
[0] => 69
[1] => 70
)
)
[2] => Array
(
[0] => Array
(
[0] => 63
)
[1] => Array
(
[0] => 65
[1] => 66
)
)
[3] => Array
(
[0] => Array
(
[0] => 66
)
)
)
并以此结束:
Array
(
[0] => 60
[1] => 68
[2] => 71
[3] => 72
[4] => 61
[5] => 69
[6] => 62
[7] => 70
[8] => 64
[9] => 63
[10] => 65
[11] => 66
[12] => 67
)
我尝试了question这样的东西:
function merge_common_keys(){
$arr = func_get_args();
$num = func_num_args();
$keys = array();
$i = 0;
for($i=0;$i<$num;++$i){
$keys = array_merge($keys, array_keys($arr[$i]));
}
$keys = array_unique($keys);
$merged = array();
foreach($keys as $key){
for($i=0;$i<$num;++$i){
if(isset($arr[$i][$key])){
$merged[] = $arr[$i][$key];
}
}
}
return $merged;
}
但是它需要传入多个数组,我无法弄清楚如何只将一个大数组提供给它并递归遍历它。
答案 0 :(得分:0)
尝试使用php 5.4 :(在使用array_column
的php 5.5上可能更短)。
function flattenAndVentilate(array $array)
{
$result = array();
foreach ($array as $array_l1) {
$copy = $array_l1;
// get level2 count()s in $copy array
array_walk($copy, function(&$value,$key){$value=count($value);});
$maxsize = max($copy);
for ($i=0;$i<$maxsize;$i++) {
foreach ($array_l1 as $array_l2) {
if (isset($array_l2[$i])) {
$result[] = $array_l2[$i];
}
}
}
}
return $result;
}
print_r(flattenAndVentilate($array));
输出:
Array
(
[0] => 60
[1] => 68
[2] => 71
[3] => 72
[4] => 61
[5] => 69
[6] => 62
[7] => 70
[8] => 64
[9] => 63
[10] => 65
[11] => 66
[12] => 66
)
答案 1 :(得分:0)
这就是我提出的:
function array_builder($array) {
$output = array();
foreach($array as $level1) {
if(count($level1) > 1) {
$counts = array();
foreach($level1 as $level2) {
$counts[] = count($level2);
}
$largest = max($counts);
$level2_count = count($level1);
for($x=0;$x<$largest;$x++) {
for($y=0;$y<$level2_count;$y++) {
if(isset($level1[$y][$x])) {
$output[] = $level1[$y][$x];
}
}
}
} else {
$output = array_merge($output,$level1[0]);
}
}
return $output;
}
print_r()
会给你这个:
Array (
[0] => 60
[1] => 68
[2] => 71
[3] => 72
[4] => 61
[5] => 69
[6] => 62
[7] => 70
[8] => 64
[9] => 63
[10] => 65
[11] => 66
[12] => 66
)