我有这段代码
$nArr = array('A', 'B', 'C', 'D', 'E', 'F');
$counter = 3;
while ($counter > 0) {
$chunkedValues[$counter][0] = 1;
for ($j = 0 ; $j < $counter ; $j++) {
$chunkedValues[$counter][$j + 1] = $nArr[$j];
}
$nArr = array_slice($nArr, $counter--);
}
var_dump($chunkedValues);
输出:
array
3 =>
array
0 => int 1
1 => string 'A' (length=1)
2 => string 'B' (length=1)
3 => string 'C' (length=1)
2 =>
array
0 => int 1
1 => string 'D' (length=1)
2 => string 'E' (length=1)
1 =>
array
0 => int 1
1 => string 'F' (length=1)
但我需要这个索引结构:
array
0 =>
array
0 => int 1
1 => string 'A' (length=1)
2 => string 'B' (length=1)
3 => string 'C' (length=1)
1 =>
array
1 => int 1
2 => string 'D' (length=1)
3 => string 'E' (length=1)
2 =>
array
2 => int 1
3 => string 'F' (length=1)
我想避免使用ceil
的循环。
有什么想法吗?谢谢你的时间。
答案 0 :(得分:2)
$nArr = array('A', 'B', 'C', 'D', 'E', 'F');
$chunkedValues = array();
$gCounter = 0;
for ($counter = 3, $start = 0; $counter > 0; $counter--, $start++) {
$arr = array($start => 1);
for ($j = 0; $j < $counter; $j++) $arr[]= $nArr[$gCounter++];
$chunkedValues []= $arr;
}
var_dump($chunkedValues);
或者,如果您不关心元素的顺序:
$nArr = array('A', 'B', 'C', 'D', 'E', 'F');
$chunkedValues = array();
$gCounter = 0;
for ($counter = 3, $start = 0; $counter > 0; $counter--, $start++) {
$arr = array_combine(
range($start+1, $counter)
array_slice($nArr, $gCounter, $gCounter += $counter);
);
$arr[$start] = 1;
$chunkedValues []= $arr;
}
var_dump($chunkedValues);
答案 1 :(得分:0)
你刚刚拆分阵列吗?
看起来您可能只能使用:
$nArr = array('A', 'B', 'C', 'D', 'E', 'F');
$chunked = array_chunk($nArr , 3);
var_dump($chunked);