Use mysql_fetch_array() with foreach() instead of while()

前端 未结 5 664
梦谈多话
梦谈多话 2020-12-05 21:49

i want to know how do we convert the following code to work with foreach

$query_select = \"SELECT * FROM shouts ORDER BY id DESC LIMIT 8;\"; 

    $result_se         


        
5条回答
  •  半阙折子戏
    2020-12-05 22:34

    There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

    $result_list = array();
    while($row = mysql_fetch_array($result_select)) {
       result_list[] = $row;
    }
    
    foreach($result_list as $row) {
       ...
    }
    

    But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

    EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

提交回复
热议问题