没有通过foreach循环得到预期的结果

时间:2017-04-02 09:39:40

标签: php mysql loops foreach

我有以下表结构

    Updates 
    +----------------------------------------------------------------------------+
    |    Id |    name    |    category    |     link    |    artist    |   home   |
    +---------------------------------------------------------------------------+
    |     1 |   song_1   |     single     |    ####     |   artist_1   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     2 |   song_2   |   bollywood    |    ####     |   artist_2   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     3 |   song_3   |     single     |    ####     |   artist_3   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     4 |   song_4   |   bollywood    |    ####     |   artist_4   |       1  |
    +------------------------------------------------------------------+

我的获取结果代码。

    <?php $update_list = $db->query('select * from `update` where home = 1 order by id desc LIMIT 0, 10');
    foreach($update_list as $field => $value)
    {
    print_r($value['category']' - ');
    if($value['link'] != '') { print_r('<a href="'.$value['link'].'" class="new5_text">'.$value['name'].'</a> - - ');
     } 
    if($value['singers'] != '') {
    print_r('['.$value['singers'].']');
    } ?>

我得到了以下结果

    single - song_1- [artist_1]
    bollywood - song_2 - [artist_2]
    single - song_3 - [artist_3]
    bollywood - song_4 - [artist_4]

我希望通过上面的单个查询得到这样的结果。

    single - song_1 - [artist_1] > song_3 - [artist_3]
    bollywood - song_2 - [artist_2] > song_4 - [artist_4]

无法弄清楚如何编码。 请帮帮我,给我一个php函数在这里使用的方法。

1 个答案:

答案 0 :(得分:0)

如果有帮助,请尝试以下代码,

<?php 
$update_list = $db->query('select * from `update` where home = 1 order by category desc, id desc LIMIT 0, 10');
$currentcategory = false;
foreach($update_list as $field => $value) {
  if($currentcategory != $value['category']) {
    if($currentcategory != false) {
      echo '<br>';
    }
    echo $value['category'].' - ';
    $currentcategory = $value['category'];
  }
  else {
    echo ' > ';
  }
  if($value['link'] != '') { 
    echo '<a href="'.$value['link'].'" class="new5_text">'.$value['name'].'</a> - ';
  }
  if($value['singers'] != '') {
    echo '['.$value['singers'].']';
  }
} ?>