迭代数组,没有按预期执行

时间:2018-02-20 13:36:10

标签: php arrays loops

我一直在努力让这个工作正确。我早些时候得到了一些帮助。但现在它不再像预期的那样表现了。

正如你所看到的,我正在从这些到数组。现在我希望它为每次迭代添加一个指向$prize数组的点。 但只有在stats数组中才会这样做,具有相似或更大的值。 现在我期望它在数组$stats中达到0值时,它会跳过,然后继续到数组中的下一个,或者重新开始。 相反,它似乎随机地将值添加到“Pig- / Slethvar”我希望它将它添加到“Torsk”

$prize = [
    "Torsk" => 0,
    "Rødspætte" => 0,
    "Mørksej" => 0,
    "Skrubbe" => 0,
    "Lubbe/Lyssej" => 0,
    "Ising" => 0,
    "Lange" => 0,
    "Makrel" => 0,
    "Hornfisk" => 0,
    "Pig-/Slethvar" => 0,
    "Havkat" => 0,
    "Laks/Havørred" => 0,
];

$stats = [
    "Torsk" => 5,
    "Rødspætte" => 5,
    "Mørksej" => 5,
    "Skrubbe" => 5,
    "Lubbe/Lyssej" => 5,
    "Ising" => 5,
    "Lange" => 5,
    "Makrel" => 5,
    "Hornfisk" => 5,
    "Pig-/Slethvar" => 5,
    "Havkat" => 5,
    "Laks/Havørred" => 0,
];

$points = 21;


for ($i = 0; $i < count($prize); ++$i) {

    foreach ($prize as $key => $value) {

       if (array_sum($prize) == $points) {
          break 2;
        }
      elseif ($stats[$key] > $prize[$key]) {
      $prize[$key]++;
        }
      elseif ($stats[$key] < $prize[$key]) {
        continue;
        }
    }
}  

foreach ($prize as $key => $value) {

    $prize_array[] = ['art' => $key, 'antal' => $value];   

}
echo json_encode($prize_array);

按要求编辑:

我最终得到以下数组:

"Torsk" => 2,
"Rødspætte" => 2,
"Mørksej" => 2,
"Skrubbe" => 2,
"Lubbe/Lyssej" => 2,
"Ising" => 2,
"Lange" => 2,
"Makrel" => 2,
"Hornfisk" => 2,
"Pig-/Slethvar" => 2,
"Havkat" => 1,
"Laks/Havørred" => 0

我的预期如下:

"Torsk" => 3,
"Rødspætte" => 2,
"Mørksej" => 2,
"Skrubbe" => 2,
"Lubbe/Lyssej" => 2,
"Ising" => 2,
"Lange" => 2,
"Makrel" => 2,
"Hornfisk" => 2,
"Pig-/Slethvar" => 1,
"Havkat" => 1,
"Laks/Havørred" => 0

0 个答案:

没有答案