使用foreach而不是while循环循环mysql_fetch_assoc

时间:2012-07-23 22:52:28

标签: php

我有一个mysql查询:

$result = mysql_query("my query");

有没有办法制作像这样的作品?

$results = mysql_fetch_assoc($result); // fetch the results

使用foreach而不是经典循环它们:

foreach($results as $result){
   $result1 = $result->result1;
   $result2 = $result->result2;
}

3 个答案:

答案 0 :(得分:3)

Foreach是一个迭代数组和对象的构造。 mysql_fetch_assoc将返回一个数组,但每个数组只有一行的数据。因此,您的foreach将简单地为您提供第一行中的列。

免于麻烦,不要一起使用mysql_fetch_assoc和foreach。

答案 1 :(得分:1)

因为mysql_fetch_assoc一次只返回一行,所以使用它将PHP结果集转换为PHP数组。然后,在阵列上使用foreach。

例如:

while ($row = mysql_fetch_assoc($result)) { 
     $rows[] = $row; 
} 

foreach($rows as $row) {
    //Then do something for each row, for e.g.:
    if ($row['col_name'] == 'somevalue'){
        $arrList[] = $row['id'];
    }
}

或者:

while ($row = mysql_fetch_assoc($result)) { 
     $rows[] = $row; 
} 

foreach($rows as $row) { 
     foreach($row as $field => $value) { 
          //do something with $field and $val 
     }
}

或者:

while ($row = mysql_fetch_assoc($result)) { 
     $rows[] = $row; 
} 

for($i=0;$i<count($rows);$i++) { 
     //do something with $rows[$i]['field_name'] 
}

来源:

Devshed: PHP foreach/while mysql result?

答案 2 :(得分:0)

请勿使用mysql(已弃用),而应使用mysqli。

$res = $mysqli->query($sql);
$rows = $res->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $id => $rowData) {
    //do something with $rowData
}
相关问题