douna3367 2014-11-23 19:53
浏览 201
已采纳

用foreach替换while循环

I have a php code like this:

$categories_query = tep_db_query("select categories_id, categories_name from categories order by categories_name");
while ($categories = mysql_fetch_array($categories_query)) {
$categories_array[] = array('id' => $categories['categories_id'], 'text' => $categories['categories_name']);
}

question is how can I replace the while loop with for example foreach so I can first fetch mysql array, then I want to edit some values and then pass it on to a loop? I tried different versions of loops but they don't give me the same result as the while loop does.

  • 写回答

3条回答 默认 最新

  • doulin9679 2014-11-23 20:13
    关注

    what you have tried looks good. there is no "fetch all" function in the old and deprecated mysql library. you should switch to mysqli or PDO instead.
    in PDO you can just grab all the result-data with $statement->fetchAll() for example.

    if you still want to solve your problem with the old mysql library, then:

    $categories_query = tep_db_query("select categories_id, categories_name from categories order by categories_name");
    while ($categories = mysql_fetch_array($categories_query)) 
    {
        $categories_array[] = array('id' => $categories['categories_id'], 'text' =>     $categories['categories_name']);
    }
    
    // do something with your $categories_array here
    
    foreach($categories_array AS $array => $row)
    {
        // you can output / access each row here e.g. with: $row['id']
        // or you can do a second foreach-loop for the columns:
        foreach($row AS $col => $data)
        {
            echo $data;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!