如何回显递增的PHP数组值

时间:2019-03-06 11:27:48

标签: php arrays loops increment

我有一个像这样的数组:

$aArray = array('one' => 0, 'two' => 0, 'three' =>0);

这样的while循环:

$x = 50;
$y = 400;

$current = current($aArray);

while ($x<$y) {
    $current++;
    $x+=50;

    if($x==$y) {
        $current = next($aArray);
    }
}

现在我要显示的是总次数递增的数组,但我不知道如何。无需使用循环就可以显示它吗?

2 个答案:

答案 0 :(得分:0)

If you want the count the number of array incremented I have added a some line of coding

$x = 50;
$y = 400;
$aArray = array('one' => 0, 'two' => 0, 'three' =>0);
$countInc=0;

$current = current($aArray);

while ($x<$y) {
    $current++;
    $x+=50;
    $countInc++;
  
    if($x==$y) {
        $current = next($aArray);
    }
}
echo "Total Number of Increment from that Array: ". $countInc;

答案 1 :(得分:0)

您可以提取数组的键,然后根据索引运行。

请考虑以下修改:

$aArray = array('one' => 0, 'two' => 0, 'three' =>0);
$keys = array_keys($aArray);

$x = 50;
$y = 400;

$i = 0;
while ($x<$y) {
    $aArray[$keys[$i]]++;
    $x+=50;

    if($x==$y) {
        $i++;
    }
}

print_r($aArray); // array('one' => 7, 'two' => 0, 'three' =>0);

如果您不想循环播放,可以这样做:

$delta = $y - $x;
$cnt = intval($delta / 50);
if ($delta % 50 != 0)
    $cnt++

现在$cnt将为7,您可以在以下位置进行设置:$aArray["one"] = $cnt;