【问题标题】:Wrap array elements in divs based on same value根据相同的值将数组元素包装在 div 中
【发布时间】:2014-09-20 20:26:34
【问题描述】:

从mysql获取结果后,是否可以将字段id_group中具有相同值的数组元素分组并包装在div元素中。谁能给我一些建议?

这是我想要的输出:

 <div class="id_group_1"> 
   <div>comment from group 1</div>
   <div>comment from group 1</div>
   <div>comment from group 1</div>
 </div>

 <div class="id_group_2">
   <div>comment from group 2</div>
   <div>comment from group 2</div>
   <div>comment from group 2</div>
   <div>comment from group 2</div>
   <div>comment from group 2</div>
 </div>

PHP

  $id_group = $_POST["group"];
  $reply = $_POST["reply"];
  $sql = "SELECT a.comments,b.name,a.id_group from `reviews` a 
          INNER JOIN `users` b 
          ON a.app_id = b.id  
          WHERE a.post_name = ? 
          AND a.id_group IN ($in) 
          ORDER BY a.id_group";

  $users = $dbh->prepare($sql);
  $users->bindValue(1,$reply);
  $i = 3;
  foreach ($id_group as $id) {
    $users->bindValue($i++, $id);
  }
  $users->execute(array_merge(array($reply), $id_group));

  //*****Here*****//
  foreach($users as $row)
  {
    echo "<div>".$row["comments"]."<br>Written by ".$row["name"]."</div>";  
  }

【问题讨论】:

    标签: php mysql loops foreach


    【解决方案1】:
    $rows = $users->fetchAll(PDO::FETCH_ASSOC);
    $arrayByGroup = array();
    
    $id = null;
    foreach ($rows as $r) {
      if($id != $r['id_group']) {
        if (!is_null($id)) {
          echo '</div>';
        }
        $id = $r['id_group'];
        echo '<div class="id_group_' . $id . '">';
      }
      echo "<div>".$r["comments"]."<br>Written by ".$r["name"]."</div>";
    
    }
    echo '</div>'
    

    根据 Matt Barrett 的见解进行编辑。

    【讨论】:

      【解决方案2】:

      由于您知道 id_groups 的值并且您已按 id_group 对结果进行排序,您可以使用 while 循环输出数据,而 id_group == id 然后使用另一个 while 循环输出下一个 div。

      这显然是一个建议,而不是一个完整而全面的答案,但我没有足够的代表来添加 cmets,所以在你提出建议时将其作为答案发布 - 希望没关系!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-24
        • 1970-01-01
        • 2020-07-25
        • 2013-03-04
        相关资源
        最近更新 更多