duanhuan1147 2013-02-06 04:42
浏览 92
已采纳

如何将此数据分组到数组中?

My table looks like this:

artist_id | song_id | user_id
a1          s1        u1
a1          s2        u1
a2          s9        u1
a3          s15       u2

I'd like my output to look something like:

Array
    (
    [u1] => Array
        (
         [a1] => Array
           (
               [0] => s1
               [1] => s2
           )
         [a2] => Array
           (
               [0] => s9
           )
   )
   [u2] => Array
        (
         [a3] => Array
           (
               [0] => s15
           )

   )

)

Where should I start?

I'm not sure my approach is most efficient:

  • Grab and group user_id, loop thru them.

  • For each user_id, grab the artist_id.

  • For each artist_id grab the song_ids underneath.

Is there a way to make this one query?

  • 写回答

2条回答 默认 最新

  • drd0833 2013-02-06 04:57
    关注

    You can get the following results set from MySQL query. Use any one of the library PDO or MySQLi.

    <?php
    $results = array(
                    0 => array('artist_id' => 'a1', 'song_id' => 's1', 'user_id' => 'u1'),
                    1 => array('artist_id' => 'a1', 'song_id' => 's2', 'user_id' => 'u1'),
                    2 => array('artist_id' => 'a2', 'song_id' => 's9', 'user_id' => 'u1'),
                    3 => array('artist_id' => 'a3', 'song_id' => 's15', 'user_id' => 'u2')
                );
    echo '<pre>';print_r($results);echo '</pre>';
    ?>
    

    Try with this,

    <?php
    $new_array = array();
    
    foreach($results as $keys=>$values) {
        $new_array[$values['user_id']][$values['artist_id']][] = $values['song_id'];
    }
    echo '<pre>';print_r($new_array);echo '</pre>';
    ?>
    

    Note: You can't get it from single query, it is depends on the results set. i explained with your result set, enter image description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题