douketangyouzh5219 2014-02-13 05:22
浏览 55

如何在while循环中获取数组元素的特定顺序

I have a table with images ('imgurl' , 'orientation') where orientation is vertical or horizontal.

I want to display images :

first horizontal first vertical second vertical second horizontal

I would usually do a

while($img2 = mysql_fetch_assoc($img))
{  ...  }

But how can I change that to control first horizontal, then first vertical, then second vertical, then second horizontal,

thanks

CODE:

$img = mysql_query("select * from blogimage where blog_id = '".$blog2['blog_id']."'  ");

while($img2 = mysql_fetch_assoc($img))
{ ?>
<tr><td colspan="2"><img src="blogimages/<? echo $img2['img_url']; ?>" /></td></tr>
<? } ?> 

the mysql table blogimage has 'img_url' and 'orientation' (vertical or horizontal)

  • 写回答

1条回答 默认 最新

  • dotj78335 2014-02-13 06:37
    关注

    There's a couple of solutions to this:

    1. Add a third column to your table called position: store the position of the element in there.

    2. If you insist doing it your way, be careful.

    $img = mysql_query("select * from blogimage where blog_id = '".$blog2['blog_id']."' ");

    Just a note don't pass unescaped strings into your SQL queries use parameter binding like PDO or framework like codeigniters active record. Also mysql is depreciated use mysqli

    if you want to alternate between vertical and horizontal store the results in an array:

    $vertical,$horizontal = array();
    while($img2 = mysql_fetch_assoc($img))
    {
    
    $orientation = mysql_fetch_assoc($orientation);
    
    if($orientation == 'vertical') {
    array_push($vertical,$img2);
    }
    else
    {
    array_push($horizontal,$img2 );
    }
    
    //now you have two arrays filled with index=>picture based on orientation
    
    for($i=0; $i<count($horizontal)-1; i++)
    {
    
    echo "<tr><td colspan='2'><img src='blogimages/'.$horizontal[$i].'/></td></tr>";
    echo "<tr><td colspan='2'><img src='blogimages/'.$vertical[$i].'/></td></tr>";
    }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题