我需要将数组拆分为4个数组。我怎样才能使它更优雅?每个元素进入子数组,而父数组不为空。
$mainblocks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$sliders = [];
$slider_index = 0;
foreach ($mainblocks as $mainblock) {
$sliders[$slider_index][] = $mainblock;
if ($slider_index >= 3) {
$slider_index = 0;
continue;
}
$slider_index++;
}
print_r($sliders);
预期输出为:[[1,5,9] [2,6,10] [3,7,11] [4,8,12]]
答案 0 :(得分:2)
看看array_chunk()
:
$input_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
print_r(array_chunk($input_array, 3)); // output: [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
说明:
array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] ) : array
将数组分为具有size元素的数组。最后一块可能包含少于size的元素。
编辑:
根据您的要求:
$mainblocks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
for($i = 0; $i <= sizeof($mainblocks) / 4; $i++)
for($j = 1; $j <= sizeof($mainblocks); $j = $j + 4)
$sliders[$i][] = $mainblocks[$j - 1 + $i];
print_r($sliders); // output: [[1,5,9] [2,6,10] [3,7,11] [4,8,12]]
答案 1 :(得分:2)
您要块并转置。
这是使用array_map()和splat运算符(...
)来解压缩块的单行代码。请注意,如果块的大小不均匀,则会得到NULL占位元素。
如果您不希望使用NULL占位符,则需要使用foreach循环而不是array_map。
代码:(Demo)
$mainblocks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var_export(array_map(null, ...array_chunk($mainblocks, 4)));
echo "\n---\n";
$mainblocks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var_export(array_map(null, ...array_chunk($mainblocks, 4)));
输出:
array (
0 =>
array (
0 => 1,
1 => 5,
2 => 9,
),
1 =>
array (
0 => 2,
1 => 6,
2 => 10,
),
2 =>
array (
0 => 3,
1 => 7,
2 => 11,
),
3 =>
array (
0 => 4,
1 => 8,
2 => 12,
),
)
---
array (
0 =>
array (
0 => 1,
1 => 5,
2 => 9,
),
1 =>
array (
0 => 2,
1 => 6,
2 => 10,
),
2 =>
array (
0 => 3,
1 => 7,
2 => NULL,
),
3 =>
array (
0 => 4,
1 => 8,
2 => NULL,
),
)