dongpalou5352 2018-03-05 14:29
浏览 86

从PHP中具有相同列值的表中获取2行

TABLE

id      m_id             image
1        1               img1.jpg
2        2               img2.jpg
3        1               img11.jpg
4        2               img22.jpg
5        1               img111.jpg

........ etc

What i need is - Get only 2 rows from the table group by m_id as below

//here getting images where m_id=1 and it is not more than 2
<section class='test'>
     <div class="n-2">
       <img src='img1.jpg'>
     </div>
     <div class="n-2">
       <img src='img11.jpg'>
     </div>
</section>


//next fetching images with m_id=2
<section class='test'>
     <div class="n-2">
       <img src='img2.jpg'>
     </div>
     <div class="n-2">
       <img src='img22.jpg'>
     </div>
</section>
  ......

What i tried is

<?php
 $query=$db->query("Select * from gallery order by m_id asc");
 $result = $query->fetchAll(\PDO::FETCH_ASSOC);

    for ($i=0; $i < count($result); $i+=2) { 
    ?>
       <section class='test'>
     <div class="n-2">
       <img src='<?php $result[$i]['image']; ?>'>
     </div>
     <div class="n-2">
       <img src='<?php $result[$i+1]['image']; ?>'>
     </div>
     </section>
   <?php
   }
?>

But i am getting all the fields to the showed section class'test', How to get the only 2 rows as showed section class.

Any experts?

  • 写回答

1条回答 默认 最新

  • duanqi6274 2018-03-05 15:03
    关注

    Hi this query will get you only two record you should read the MySql tutorials in w3schools.com

    Select * from gallery order by m_id asc LIMIT 2
    

    Update 1: this will work hopefully in your case.

    $query = $db->query("Select * from gallery order by m_id asc");
    $items = $query->fetchAll(\PDO::FETCH_ASSOC);
    
    $result = [];
    $temp = [];
    foreach ($items as $item) {
        $m_id = $item['m_id'];
        if (!isset($temp[$m_id]) || count($temp[$m_id]) < 2) {
            $temp[$m_id][] = $item['image'];
            $result = $item['image'];
        }
    }
    
    for ($i = 0; $i < count($result); $i += 2) {
        ?>
        <section class='test'>
            <div class="n-2">
                <img src='<?php $result[$i]['image']; ?>'>
            </div>
            <div class="n-2">
                <img src='<?php $result[$i + 1]['image']; ?>'>
            </div>
        </section>
        <?php
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?