嘿我有一组从数据库返回的结果,它们是代表1-18的数字,它们是drivers_id,它可以返回任意数量的那些取决于从竞赛中退出的驱动程序数量。然后我将它们与用户驱动程序匹配,如果它们匹配则从用户点匹配到-10点。
如果它们不匹配则为+5分。如果查询根本没有返回任何设置,那么我知道用户四个驱动程序每个可以+5个点,但如果它返回5个行,那么我如何循环它们并匹配它们?如果没有匹配,则向该驱动程序变量添加+5个点,但必须在比较所有结果集之后,因为该驱动程序可能与$ row中的下一行匹配。非常感谢您提供的任何帮助!。
p.s结果集中的每个driver_id都是唯一的,所以一旦进行比较 是的,那么driver_id将不再出现。
$results = mysql_query("SELECT drivers_id FROM results_retired WHERE drivers_id IN ('$driver1', '$driver2', '$driver3', '$driver4') AND track_id = '$track'") or die ("Failed to update" . mysql_error());
$retireddrivers = mysql_fetch_array($results)
if(in_array($driver1, $retireddrivers)){
$driveronepoints -= $driver_points_system["retired"];
}
else {
$driveronepoints += $driver_points_system["completion"];
}
if(in_array($driver2, $retireddrivers)) {
$drivertwopoints -= $driver_points_system["retired"];
}
else {
$drivertwopoints += $driver_points_system["completion"];
}
if(in_array($driver3, $retireddrivers)) {
$driverthreepoints -= $driver_points_system["retired"];
}
else {
$driverthreepoints += $driver_points_system["completion"];
}
if(in_array($driver4, $retireddrivers)) {
$driverfourpoints -= $driver_points_system["retired"];
}
else {
$driverfourpoints += $driver_points_system["completion"];
}
我现在对代码做了一些更改,在这个实例中是否可以使用in_array函数?
感谢
答案 0 :(得分:1)
看起来你错过了行与列的概念。
mysql_fetch_*
会在每次调用时返回一行 - 即一个已退役的驱动程序ID。在使用in_array
之前,您需要将它们收集到一个数组中。
while ($retired_driver = mysql_fetch_array($results))
{
$retireddrivers[] = $retired_driver['driver_id'];
}
另外,如果你可以管理它,我也会考虑将驱动程序1-4放入一个数组中。那么你可以这样做
// Ideally, $driver[1-4]* won't exist at all -- you'd pull the info from the DB,
// or from the form, and stuff it directly into the array.
// This code right here is just to make existing code work
$drivers = array(
array('id' => $driver1, 'points' => &$driver1points),
array('id' => $driver2, 'points' => &$driver2points),
array('id' => $driver3, 'points' => &$driver3points),
array('id' => $driver4, 'points' => &$driver4points),
);
foreach ($drivers as $driver)
{
if (in_array($driver['id'], $retireddrivers))
{
$driver['points'] -= $driver_points_system['retired'];
}
else
{
$driver['points'] += $driver_points_system['completion'];
}
}
大大减少了代码的重复。