我有一个表单,用户输入6个数字,然后我使用SimpleXML将输入的数字与xml元素进行比较。如果找到正确的数字,则它将存储在变量中($ n1 - $ n6)。变量在foreach循环外部使用,以确定所有6个数字是否正确,然后回显元素的日期和累积奖金。这可以正常工作。
如果输入的数字与xml元素不匹配,我想回显错误的结果(“抱歉”)。但是,这部分不起作用,因为它仍然回显了与xml中的数字无关的日期和累积奖金。它会产生一个随机日期和累积奖金编号,它们不存储在xml文件中。
如果输入6个不正确的数字,结果是错误的并且回显“抱歉”,我将如何确保?
XML:
<lottery>
<number>
<date>7.11.2015</date>
<num1>2</num1>
<num2>3</num2>
<num3>34</num3>
<num4>43</num4>
<num5>49</num5>
<num6>50</num6>
<jackpot>13156375</jackpot>
</number>
<number>
<date>08.11.2015</date>
<num1>11</num1>
<num2>13</num2>
<num3>18</num3>
<num4>25</num4>
<num5>29</num5>
<num6>47</num6>
<jackpot>8842605</jackpot>
</number>
</lottery>
PHP:
$n1 = false;//make true once we find 1st num
$n2 = false;//make true once we find 2nd num
$n3 = false;
$n4 = false;
$n5 = false;
$n6 = false;
$xml = simplexml_load_file('lottery2.xml') or die("Error: Cannot create object");
if (isset($_POST['num1']) && isset($_POST['num2'])) {
foreach ($xml->children() as $record) {
$n1 = $n1 || $record -> num1 == $num1 || $record -> num2 == $num1 || $record -> num3 == $num1 || $record -> num4 == $num1 || $record -> num5 == $num1 || $record -> num6 == $num1;
$n2 = $n2 || $record -> num1 == $num2 || $record -> num2 == $num2 || $record -> num3 == $num2 || $record -> num4 == $num2 || $record -> num5 == $num2 || $record -> num6 == $num2;
$n3 = $n3 || $record -> num1 == $num3 || $record -> num2 == $num3 || $record -> num3 == $num3 || $record -> num4 == $num3 || $record -> num5 == $num3 || $record -> num6 == $num3;
$n4 = $n4 || $record -> num1 == $num4 || $record -> num2 == $num4 || $record -> num3 == $num4 || $record -> num4 == $num4 || $record -> num5 == $num4 || $record -> num6 == $num4;
$n5 = $n5 || $record -> num1 == $num5 || $record -> num2 == $num5 || $record -> num3 == $num5 || $record -> num4 == $num5 || $record -> num5 == $num5 || $record -> num6 == $num5;
$n6 = $n6 || $record -> num1 == $num6 || $record -> num2 == $num6 || $record -> num3 == $num6 || $record -> num4 == $num6 || $record -> num5 == $num6 || $record -> num6 == $num6;
if ($n1 && $n2 && $n3 && $n4 && $n5 && $n6) break; //Found match. No need to keep looking
}//end foreach
if ($n1 && $n2 && $n3 && $n4 && $n5 && $n6)
{
echo $record -> date;
echo $record -> jackpot;
}
else
{
echo "Sorry no winnings";
}
答案 0 :(得分:0)
如果认为你应该考虑使用数组而不是庞大的if
语句。
我会这样做:
示例代码:
$xml = simplexml_load_file('lottery2.xml') or die("Error: Cannot create object");
if(isset($_POST['num1']) && isset($_POST['num2'])) {
$myList = array($num1, $num2, $num3, $num4, $num5, $num6);
$result = array();
$win = 0;
sort($myList);
foreach ($xml->children() as $record) {
for($n = 0; $n < 6; $n++) {
$result[$n] = (int)$record -> {'num'.($n + 1)};
}
sort($result);
if (match($myList, $result)) {
echo $record -> date;
echo $record -> jackpot;
$win++;
}
}
if($win == 0) {
echo "Sorry no winnings";
}
}
function match ($list1, $list2) {
for($n = 0; $n < 6; $n++) {
if($list1[$n] != $list2[$n]) {
return false;
}
}
return true;
}