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条)

报告相同问题?

悬赏问题

  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制