【问题标题】:Not getting expected results through foreach loop未通过 foreach 循环获得预期结果
【发布时间】:2017-04-02 09:39:40
【问题描述】:

我有以下表结构

    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函数。

【问题讨论】:

    标签: php mysql loops foreach


    【解决方案1】:

    如果有帮助,试试下面的代码,

    <?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'].']';
      }
    } ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 2021-11-03
      • 2013-05-06
      • 1970-01-01
      • 2015-07-13
      相关资源
      最近更新 更多