好吧我使用这个foreach循环来解析xml以将结果数据添加到我的数据库中我需要设置$win值但它总是返回3时它不应该...
$myinfo = simplexml_load_file('http://mysite/results.xml'); foreach ($myinfo->Event as $info): $cid=$info['EventID']; $a=$info->Match['AScoreNT']; $b=$info->Match['BScoreNT']; if($a > $b){ $win =1; } elseif($a < $b){ $win =2; } else{ $win =3; } $sql = " INSERT IGNORE INTO `engine4_event_wins` SET `win_result` = $win, `comp_id` = $cid; "; mysql_query($sql); endforeach; <MyFeed> <Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651239" FinalDate="2012-09-07T00:00:00"> <Match TeamA="Hawthorn" TeamB="Collingwood" AScoreNT="135" BScoreNT="97"/> </Event> <Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651240" FinalDate="2012-09-08T00:00:00"> <Match TeamA="Adelaide Crows" TeamB="Sydney Swans" AScoreNT="42" BScoreNT="71"/> </Event> </MyFeed>Ok im using this foreach loop to parse xml to add result data into my database I need to set the $win value but it always return 3 when it shouldnt b..
$myinfo = simplexml_load_file('http://mysite/results.xml'); foreach ($myinfo->Event as $info): $cid=$info['EventID']; $a=$info->Match['AScoreNT']; $b=$info->Match['BScoreNT']; if($a > $b){ $win =1; } elseif($a < $b){ $win =2; } else{ $win =3; } $sql = " INSERT IGNORE INTO `engine4_event_wins` SET `win_result` = $win, `comp_id` = $cid; "; mysql_query($sql); endforeach; <MyFeed> <Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651239" FinalDate="2012-09-07T00:00:00"> <Match TeamA="Hawthorn" TeamB="Collingwood" AScoreNT="135" BScoreNT="97"/> </Event> <Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651240" FinalDate="2012-09-08T00:00:00"> <Match TeamA="Adelaide Crows" TeamB="Sydney Swans" AScoreNT="42" BScoreNT="71"/> </Event> </MyFeed>最满意答案
echo显$a和$b的值,看看为什么它总是等于:)
你可以做的另一件事是:
foreach ($myinfo->Event as $info): $a=$info->Match['AScoreNT']; $b=$info->Match['BScoreNT']; if($a === $b){ $win =3; elseif($a > $b){ $win =1; } elseif($a < $b){ $win =2; } else{ $win =4; } echo $win; endforeach;我的猜测是它会打印4 ...
更新: 我的怀疑是正确的,你是比较字符串而不是整数,这就是为什么你得到equal结果(双方都不是空字符串,因此,根据PHP - 它们是相似的......我知道,这不直观,我建议阅读它 !)。
要修复它,请将代码更改为:
if((int)$a > (int)$b){ $win =1; } elseif((int)$a < (int)$b){ $win =2; } else{ $win =3; }echo the values of $a and $b and see why it's always equals :)
Another thing you can do is:
foreach ($myinfo->Event as $info): $a=$info->Match['AScoreNT']; $b=$info->Match['BScoreNT']; if($a === $b){ $win =3; elseif($a > $b){ $win =1; } elseif($a < $b){ $win =2; } else{ $win =4; } echo $win; endforeach;My guess is that it'll print 4...
Update: My suspicious was correct, you're comparing strings instead of ints, that's why you get the equal result (both sides are not empty strings, hence, according to PHP - they are similar... I know, it's not intuitive, I recommend reading about it!).
In order to fix it, change your code to:
if((int)$a > (int)$b){ $win =1; } elseif((int)$a < (int)$b){ $win =2; } else{ $win =3; }更多推荐
发布评论