在php中对给定数字的数组元素进行分组 如何使用php对数组元素进行分组?
我有以下数组
array (size=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
我需要按照模型
对这个数组进行分组0 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
1 =>
array (size=3)
0 => int 4
1 => int 5
2 => int 6
2 =>
array (size=3)
0 => int 7
1 => int 8
2 => int 9
3 =>
array (size=3)
0 => int 10
我该怎么办?
我尝试了以下代码。
$arr = array(1,2,3,4,5,6,7,8,9,10);
$result = array();
for ($i = 0; $i < count($arr); $i++) {
for ($j = 0; $j < 3; $j++) {
$result[$i][] = $arr[$j];
}
}
结果是下面给出的代码
array (size=10)
0 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
1 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
2 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
3 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
4 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
5 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
6 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
7 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
8 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
9 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 3
答案 0 :(得分:0)
<?php
$array = array(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
5 => 6,
6 => 7,
7 => 8,
8 => 9,
9 => 10
);
print_r(array_chunk($array, 3));
答案 1 :(得分:-1)
我认为这就是你所需要的。 https://www.w3schools.com/php/func_array_chunk.asp