2

私は2つの別々の配列から3つ以上の数字を一致させようとしていますが、これまでのところ、6つの数字すべてを比較して3つが共通しているかどうかを確認する必要がある場合、最初の3つの数字に一致するコードしかありませんか? 6 つの数値すべてを比較してみましたが、うまくいきません。どんな助けでも大歓迎です。ジェシカ

foreach($lottoTickets as $y => $yvalue)
{   
if($i == 0)
{
    echo " ";
}
else{
    if((($winner[0] == $lottoTickets[$y][0]) || ($winner[0] ==   $lottoTickets[$y][1]) || ($winner[0] == $lottoTickets[$y][2]) || ($winner[0] == $lottoTickets[$y][3]) || ($winner[0] == $lottoTickets[$y][4]) || ($winner[0] == $lottoTickets[$y][5])) && 
    (($winner[1] == $lottoTickets[$y][0]) || ($winner[1] == $lottoTickets[$y][1]) || ($winner[1] == $lottoTickets[$y][2]) || ($winner[1] == $lottoTickets[$y][3]) ||($winner[1] == $lottoTickets[$y][4]) || ($winner[1] == $lottoTickets[$y][5])) &&
    (($winner[2] == $lottoTickets[$y][0]) || ($winner[2] == $lottoTickets[$y][1]) || ($winner[2] == $lottoTickets[$y][2]) || ($winner[0] == $lottoTickets[$y][3]) ||($winner[2] == $lottoTickets[$y][4]) || ($winner[2] == $lottoTickets[$y][5])))

    echo "<b>Three winning numbers ID = </b>" .$y;
}
4

1 に答える 1

1

You could use array_diff() for that purpose. It returns an array containing all differences within two given arrays.

If you determine the differences between the user's lotto ticket and the correct numbers, you get the amount of wrong numbers.

Subtracting that integer from 6* gives you the amount of correctly chosen numbers.

foreach ($lottoTickets as $y => $yvalue) {
  if($i == 0)
  {
    echo " ";
  }

  else {
    $diff = array_diff($lottoTickets[$y], $winner);
    $correctNumbers = 6 - count($diff);

    if ($correctNumbers >= 3) {
      echo "<b>(At least) three winning numbers ID = </b>" . $y;
    }
  }
}

Here is also a minimal working sample: http://codepad.org/OWrdv5Xe

*) 6 is not a magic number here (→ Lotto)


As for why your code does not work (in all cases): it is because you only compare the first three correct numbers to the chosen ones. You have to compare all numbers. This involves having a counter variable for storing the amount of correctly chosen numbers.

If you really want to stick with your current solution, at least use in_array() and a loop. But the solution I provided at the top of my answer is really better.

于 2013-10-06T16:43:30.560 に答える