我有一个这样的数组:
$arrayToFill=['a','b','c','d','e','f','g','h','k','l','m','n','o','p','r','u','w','x','y','z'];
所以有20个元素,我希望数组$batchArray
在迭代后看起来像这样:
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
[1] => Array
(
[0] => f
[1] => g
[2] => h
[3] => k
[4] => l
)
)
[1] => Array
(
[0] => Array
(
[0] => m
[1] => n
[2] => o
[3] => p
[4] => r
)
[1] => Array
(
[0] => u
[1] => w
[2] => x
[3] => y
[4] => z
)
)
)
所以在第六,第十一等元素上制作了新的子阵列,在该子阵列的第二个上,制作了更大的阵列。以下是我尝试过的方法以及到目前为止我所做的:
$a=0;
$i=0;
$arrayToFill=['a','b','c','d','e','f','g','h','k','l','m','n','o','p','r','u','w','x','y','z'];
$batchArray=[];
$batchArray[$a]=[];
$batchArray[$a][$i]=[];
if($i==0){
$currentNumber = ($i+1)*5;
}else{
$currentNumber = 5;
}
$currentNumberOfBathes=count($batchArray[$a])+1;
$currentNumberBatch = 2;
foreach($arrayToFill as $array){
$numberOfElements=count($batchArray[$a][$i]);
$currentNumberOfBathes=count($batchArray[$a])+1;
if($numberOfElements>$currentNumber && $numberOfElements<$currentNumber+2){
echo 'desilo se';
echo $i;
$i++;
$batchArray[$a][$i]=[];
}
array_push($batchArray[$a][$i],$array);
}
所以这就是我得到的:
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[1] => Array
(
[0] => g
[1] => h
[2] => k
[3] => l
[4] => m
[5] => n
)
[2] => Array
(
[0] => o
[1] => p
[2] => r
[3] => u
[4] => w
[5] => x
)
[3] => Array
(
[0] => y
[1] => z
)
)
)
首先,在某处丢失的信件很少。当我试图限制这个包含5个字母的子数组时,将其索引增加到第三个,如下所示:
foreach($arrayToFill as $array){
$numberOfElements=count($batchArray[$a][$i]);
$currentNumberOfBathes=count($batchArray[$a])+1;
if($numberOfElements>$currentNumber && $numberOfElements<$currentNumber+2){
$i++;
$batchArray[$a][$i]=[];
}
if($currentNumberOfBathes>$currentNumberBatch && $currentNumberOfBathes<$currentNumberBatch+2){
$a++;
$batchArray[$a]=[];
}
array_push($batchArray[$a][$i],$array);
}
我收到此输出并发出警告:
Warning: array_push() expects parameter 1 to be array, null given
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[1] => Array
(
[0] => g
)
)
[1] => Array
(
[1] =>
)
)
那么,这里发生了什么以及为什么更大的谜团。请帮忙
答案 0 :(得分:3)
只需使用array_chunk()
几次即可大大简化此操作。第一次将其拆分为数组数组,后者每个最多包含5个元素。然后第二次将 分成两个元素的数组。
比说它更容易看到:
print_r(array_chunk(array_chunk($arrayToFill, 5), 2));
结果:
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
[1] => Array
(
[0] => f
[1] => g
[2] => h
[3] => k
[4] => l
)
)
[1] => Array
(
[0] => Array
(
[0] => m
[1] => n
[2] => o
[3] => p
[4] => r
)
[1] => Array
(
[0] => u
[1] => w
[2] => x
[3] => y
[4] => z
)
)
)