douchun9719 2012-02-07 14:03
浏览 169
已采纳

多个for循环 - 如何打印数据

i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.

  • 写回答

6条回答 默认 最新

  • dqnz43863 2012-02-07 14:28
    关注

    a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)

    $query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
    $all_items = array();
    while($row=mysql_fetch_array($query)){
       if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
           $all_items[$row['category']] = "";
       }
       $all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
    }
    

    Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:

    echo  $all_items['category name'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器