分组和foreach

时间:2016-03-23 01:06:58

标签: php sql foreach group-by

我想只打印一次标题和所有相关图片id_post

表格图片

id_images | dir_image | post_id
     1      image1.jpg   1
     2      image2.jpg   1
     3      image3.jpg   1
     4      image4.jpg   1
     5      image5.jpg   2
     6      image6.jpg   2
     7      image7.jpg   2
     8      image8.jpg   2

表格POSTS

id_post   |          slug        |   title
 1           title_post            Title Post 
 2           title_post_2          Title Post 2

PHP代码:

$slug = $_GET['slug'];
 $stmt = $DB_con->prepare("SELECT * FROM posts, images 
                      WHERE posts.id_post = images.post_id 
                      AND slug=:slug");
 $stmt->execute(array(":slug"=>$_GET['slug']));

 while($row=$stmt->fetch(PDO::FETCH_BOTH))
 {
 ?> 

<h1><?php print utf8_encode($row['title']);?></h1>


<?php
}
?>

访问“Title post 2”页面,结果是:

Title post 2
image5.jpg

Title post 2
image6.jpg

Title post 2
image7.jpg

Title post 2
image8.jpg

如何获得结果:

Title post 2
image5.jpg
image6.jpg
image7.jpg
image8.jpg

我如何输入SQL分组“group by”来分组图像:

SELECT * FROM posts, images 
                     WHERE posts.id_post = images.post_id 
                     AND slug=:slug

然后在插入一个带有该组图像的foreach的时候?

while($row=$stmt->fetch(PDO::FETCH_BOTH))
     {
     ?> 

    <h1><?php print utf8_encode($row['title']);?></h1>


    <?php
    }
    ?>

如果不解决我的插入,则需要创建几个ifs

2 个答案:

答案 0 :(得分:1)

如果你只想在程序PHP中这样做,你可以这样做:

$runningTitle = '';

while($row=$stmt->fetch(PDO::FETCH_BOTH)) { 

    if ($row['title'] != $runningTitle) {
        $runningTitle = $row['title'];
        print "<h1>";
        print utf8_encode($row['title']);
        print "</h1>";
    }

    // now render images.

}

但是我建议使用更面向对象的方法来构建html字符串,然后将其作为单个字符串返回,最后回显,而不是在程序上渲染所有内容。在渲染页面之前完成所有程序逻辑通常更整洁,而不是在您仍然要求代码做出决策时进行渲染。

您正在使用PHP的传统形式 - 作为模板语言。从那以后,它已经走了很长的路。

答案 1 :(得分:1)

它有些简单快速,如果你加入&#34;图像很少,而不是很多。

您的小组,使用GROUP BY并获取SEPARATOR与GROUP_CONCAT连接的所有图片

SELECT 
  posts.*,
  COUNT(0) total, 
  GROUP_CONCAT(dir_image SEPARATOR '|') images
FROM 
  posts
  INNER JOIN images ON (posts.id_post = images.post_id )
WHERE
  slug=:slug
GROUP BY
  id_post

这是你的循环,创建一个数字爆炸隔离区域上的分离器&#34;图像&#34;并做循环

while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>
    <h1><?php print utf8_encode($row['title']); ?></h1>
    <div>
        <ul>
        <?php
            echo '<li>' . implode('</li><li>', $aImages) . '</li>'
        ?>
        </ul>
    </div>
    <?php
}
?>

或者

while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>
    <h1><?php print utf8_encode($row['title']); ?></h1>
    <div>
        <?php
        foreach ($aImages as $sImage) {
        ?>
            <a href="<?php echo $sImage;?>"><?php echo $sImage; ?></a>
        <?php
        }
        ?>
    </div>
    <?php
}
?>
相关问题