访问PHP数组项值

时间:2017-03-08 12:30:52

标签: php

我有以下脚本将总数除以人数并将结果存储在数组中。

不是在最后转储$result数组,我想知道是否可以在for循环中回显每个数组项的值?

// initial conditions
$total = 1001;
$people = 5;

// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);

// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
for ($i = 0; $i < $overheads; $i++) {
    $result[$i]++;
}

// voila...
var_dump($result);

因此,上面的脚本应该循环:

200
200
200
200
201

非常感谢任何指示。

2 个答案:

答案 0 :(得分:1)

从技术上讲,你不能“回显每个数组项的值 在for循环,因为它因为你没有填充数组 在一个循环中,你正在填充array_fill()。你拥有的循环就是 与其余人一起工作。如果你在那里回应,你就会偏袒 结果。所以要么保留你的代码并在最后回显值, 用简单的一句:

foreach ($result as $r) echo "$r\n";

或者您修改代码以另一种方式填充数组。哪一个 可能很有趣。请注意,您忘记了模数 运算符%,用于除法的剩余部分。这一行:

$overheads = $total - $value * $people;

可以简单地写成:

$overheads = $total % $people;

填写循环的想法:

// initial conditions
$total = 1001;
$people = 5;

$value = floor($total/$people);
$overheads = $total % $people;

foreach (range(1, $people) as $p) {
    $r = $value;
    if ($overheads) {
        # if there is still remainders:
        $r++;
        $overheads--;
    }
    # echo the value and also store it
    echo "$r\n";
    $result[] = $r;
}

答案 1 :(得分:1)

// initial conditions
$total = 1001;
$people = 5;

// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);

// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;

$i = 1;
foreach($result as $res)
{

    if ($i < $people){
     echo $res . "\n";
    }else{
        echo $res + 1 . "\n";
    }
   $i++;
}

//瞧......