Php 用特定的数字填充数组
我需要用数字填充数组,举几个例子:Php 用特定的数字填充数组,php,arrays,Php,Arrays,我需要用数字填充数组,举几个例子: NBREPARCHARGE=4;十年 预期输出:$niveaux=array(4,4,2)4+4+2=10 nReparCharge=6;14天 预期输出:$niveaux=array(6,6,2)6+6+2=14 NBREPARCHARGE=16;十三 预期输出:$niveaux=array(13)13=13 NBREPARCHARGE=4;30年 预期输出:$niveaux=array(4,4,4,4,4,2)4+4+4+4+4+4+4+4
- NBREPARCHARGE=4;十年
- 预期输出:
$niveaux=array(4,4,2)代码>4+4+2=10
- 预期输出:
- nReparCharge=6;14天
- 预期输出:
$niveaux=array(6,6,2)代码>6+6+2=14
- 预期输出:
- NBREPARCHARGE=16;十三
- 预期输出:
$niveaux=array(13)代码>13=13
- 预期输出:
- NBREPARCHARGE=4;30年
- 预期输出:
$niveaux=array(4,4,4,4,4,2)代码>4+4+4+4+4+4+4+4+4+2=30
- 预期输出:
function chargement($nbre, $nbreParChargement){
$niveaux = array();
for($i=0; $i<=$nbre; $i++){
$niveaux[$i] = $i + $nbreParChargement;
}
}
功能计费($nbre,$NBREPARCHARGE){
$niveaux=array();
对于($i=0;$i另一个实现,对于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));
用$nbre/$NBREPARCHARGE
项和$NBREPARCHARGE
的值填充数组。最后一个值是$nbre
与其他元素之和之间的差值,由$NBREPARCHARGE*floor($nbre/$NBREPARCHARGE)
给出,该值始终大于0
这只适用于php>=5.6,因为array\u 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;
}
.试试这个:
<?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);
按照以下步骤解决您的问题:
计算NbreparCharge向数组中添加数字的次数
将该数字添加到数组中的次数(n)
计算给定值和我们的总值的差值(以值为单位)
若Diff大于0,则表示缺少Diff编号,将该编号添加到数组中并返回
这些数字的规则是什么?随机数?遵循公式的数字?请记住将变量和函数名翻译成英语,否则非法语国家的人可能很难理解您的代码。当代码适用于所有提到的情况时,为什么会被否决?虽然这段代码片段可以解决问题,但实际上ly有助于提高你的文章质量。记住,你是在回答将来读者的问题,而这些人可能不知道你的代码建议的原因。理解。足够公平。感谢你提供的信息。此代码有什么问题?:X,给出-1,然后留下评论,大声吼叫ans。如果你愿意这样做,不可以“我想回答您在功能中遇到的问题。@Kyll,检查代码,我对每一行发布的代码都给出了注释,在向下投票之前,请检查一次,发布了哪些人。@Kyll,添加了说明。”
<?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
)