我需要用数字填充数组,例如:
nbreParChargement = 4;对于10
EntityFramework
4 + 4 + 2 = 10 nbreParChargement = 6;对于14
"EntityFramework": "6.1.3",
"EntityFramework.SqlServer": "7.0.0-beta6",
"EntityFramework.Commands": "7.0.0-beta6",
6 + 6 + 2 = 14 nbreParChargement = 16;对于13
$niveaux = array(4,4,2);
13 = 13 nbreParChargement = 4; 30岁
$niveaux = array(6,6,2);
4 + 4 + 4 + 4 + 4 + 4 + 4 + 2 = 30 我试图解决这个问题,但我不知道完美的解决方案:
$niveaux = array(13);
答案 0 :(得分:2)
另一个实现,两行代码,用于php> = 5.6:
function chargement($nbre, $nbreParChargement){
$niveaux = array_fill(0, floor($nbre/$nbreParChargement), $nbreParChargement);
$niveaux[] = $nbre - array_sum($niveaux);
return $niveaux;
}
var_dump(chargement(10, 4));
var_dump(chargement(14, 6));
var_dump(chargement(13, 16));
var_dump(chargement(30, 4));
array_fill
使用$nbre/$nbreParChargement
条目填充数组$nbreParChargement
的数组。最后一个值是$nbre
与$nbreParChargement * floor($nbre/$nbreParChargement)
给出的其他元素之和之间的差异,它始终是> 0
这项工作仅适用于php> = 5.6,因为array_fill
仅从该版本接受0
为num
。以前,num
必须大于零。
所以,对于任何版本的php:
function chargement($nbre, $nbreParChargement){
$niveaux = array();
if ($n = floor($nbre/$nbreParChargement)) {
$niveaux = array_fill(0, $n, $nbreParChargement);
}
$niveaux[] = $nbre - array_sum($niveaux);
return $niveaux;
}
答案 1 :(得分:1)
<?php
function chargement($nbre, $nbreParChargement){
$niveaux = array();
$n=(int)($nbre/$nbreParChargement);//Calculating how many times to $nbreParChargement add number to an array.
for($i=0;$i<$n;$i++){
$niveaux[]=$nbreParChargement;//Adding $nbreParChargement value to array
}
$diff=$nbre-array_sum($niveaux);//Calculating diff of given and our calculated value
if($diff!=0){//If the diff value is >0 then adding the remaining that value to an array
$niveaux[]=$diff;
}
return $niveaux; //Returning array
}
print_r(chargement(14,4));
输出:
Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 2
)
按照以下步骤解决您的问题:
答案 2 :(得分:-1)
试试这个:
<?php
function chargement($nbre, $nbreParChargement){
$niveaux = array();
if($nbreParChargement <= $nbre) {
$repetitionCount = floor($nbre / $nbreParChargement);
$remainder = $nbre % $nbreParChargement;
for($i = 0; $i < $repetitionCount; $i++){
$niveaux[] = $nbreParChargement;
}
if(!empty($remainder)) {
$niveaux[] = $remainder;
}
} else {
$niveaux[] = $nbre;
}
return $niveaux;
}
$array = chargement(13, 16);
echo '<pre>';
print_r($array);