1
我有一個這樣的數組:如何將數組的每個第n個元素排序爲不同的子陣列?
$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] =>
)
)
那麼,是什麼在這裏發生,爲什麼連更大的謎團。請幫助
燁,這有助於..謝謝! – Ognj3n