我有3个这样的数组:
$a = array(
0 => 'a1',
1 => 'a2',
2 => 'a3'
);
$b = array(
0 => 'b1',
1 => 'b2',
2 => 'b3'
);
$c = array(
0 => 'c1',
1 => 'c2',
2 => 'c3'
);
我喜欢这样的东西:
$r = array(
0 => 'a1',
1 => 'b1',
2 => 'c1',
3 => 'a2',
4 => 'b2',
5 => 'c2',
6 => 'a3',
....
...
);
我怎样才能做到这一点并享受使用超过 3 个输入数组的能力?
编辑:
我试过这个:
$a = array(
0 => 'a1',
1 => 'a2',
2 => 'a3',
3 => 'a4'
);
$b = array(
0 => 'b1',
1 => 'b2',
2 => 'b3'
);
$c = array(
0 => 'c1',
1 => 'c2',
2 => 'c3',
3 => 'c4',
4 => 'c5',
5 => 'c6'
);
$l['a'] = count($a);
$l['b'] = count($b);
$l['c'] = count($c);
arsort($l);
$largest = key($l);
$result = array();
foreach ($$largest as $key => $value) {
$result[] = $a[$key];
if(array_key_exists($key, $b)) $result[] = $b[$key];
if(array_key_exists($key, $c)) $result[] = $c[$key];
}
print_r($result);
输出:Array ( [0] => a1 [1] => b1 [2] => c1 [3] => a2 [4] => b2 [5] => c2 [6] => a3 [7] => b3 [8] => c3 [9] => a4 [10] => c4 [11] => [12] => c5 [13] => [14] => c6 )
这可行,但代码不好。有没有人有更好的解决方案?
解决方案: 我用一些动态功能更新了@salathe 的帖子
function comb(){
$arrays = func_get_args();
$result = array();
foreach (call_user_func_array(array_map, $arrays) as $column) {
$values = array_filter($column, function ($a) { return $a !== null; });
$result = array_merge($result, $values);
}
return $result;
}
print_r(comb(null,$a,$b,$c,$d,....));