doushouxie7064 2017-09-29 13:51
浏览 54
已采纳

将平面数组转换为按类别分组的数组

I've got a database table that looks like this:

uid | group  | category
1   | group1 | cat1
2   | group1 | cat2
3   | group2 | cat3
4   | group2 | cat4
5   | group2 | cat5
6   | group3 | cat6
7   | group3 | cat7

But I need this data in an array, that groups categories by their group.

For example, my array should look like this:

Array
(
    [group1] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => cat1

                )

            [1] => Array
                (
                    [0] => 2
                    [1] => cat2
                )

        )

    [group2] => Array
        (
            [0] => Array
                (
                    [0] => 3
                    [1] => cat3
                )

            [1] => Array
                (
                    [0] => 4
                    [1] => cat4
                )

            [2] => Array
                (
                    [0] => 5
                    [1] => cat5
                )

        )

    [group3] => Array
        (
            [0] => Array
                (
                    [0] => 6
                    [1] => cat6
                )
            [1] => Array
                (
                    [0] => 7
                    [1] => cat7
                )

        )

)

I've written a foreach loop that does just this, but I have a problem.

My problem is that it always leaves out the very last row of the table, and I'm not sure how to fix it. In my mind, the logic dictates that it should always work.

I was thinking that after the loop I could just add the very last row to the new array, but I think that may cause issues if the last row has a different group, and I would rather the solution be built into the foreach loop.

Unfortunately, I am at a loss here. How can I fix my code to include the very last row of the database query?

I would also be interested to see what improvements I can make on my current code, but that may be a better question for codereview.

My loop:

$pass = [];
foreach($stmt as $key => $value) {
    if(empty($currentGroup)) $currentGroup = $value['group'];
    if(empty($temp)) $temp = [];
    if($currentGroup != $value['group'] || $key+1 == count($stmt)) {
        $pass[$currentGroup] = $temp;
        $currentGroup = $value['group'];
        $temp = [];
        $temp[] = [$stmt[$key]['uid'], $stmt[$key]['category']];
    } else {
        $temp[] = [$stmt[$key]['uid'], $stmt[$key]['category']];
    }
}
  • 写回答

2条回答 默认 最新

  • dsxz84851 2017-09-29 13:54
    关注

    The following should do it:

    <?php
    
    //Create an array to store our grouped rows
    $grouped = array();
    
    //Loop over all rows returned by the $stmt that has been executed.
    //You could probably remove the key from here, it's not needed it seems.
    //The keys within the $value array will match the names of the columns in 
    //the database,
    foreach($stmt as $key => $value){
    
        //As we're storing by the group value from the row we first want to
        //check if our grouped array contains a key for the group of the row
        //being processed. If it does not, create an empty array within the
        //grouped data for this group.
        if(!array_key_exists($value['group'], $grouped)){
            $grouped[$value['group']] = array();
        }
    
        //Knowing we will always have an array element for the rows group
        //we can blindly append the values for this row to the grouped 
        //container using its values.
        //'[] =' is just short hand append.
        $grouped[$value['group']][] = array(
            $value['uid'],
            $value['category']
        );
    }
    

    Hope that helps!


    To further future proof this loop you could change the grouped value append to the following:

    <?php
    
    //Setting the whole row (minus the group) rather than just the uid 
    //and category explicitly allows this code to work without modification
    //as the datatable changes, ie. new columns. Assuming that is the 'group'
    //column remains present
    unset($value['group']);
    $grouped[$value['group']][] = $value;
    

    Grouped contents data could now be accessed using the following:

    <?php
    
    //Acceess data via column name not array index, yay!
    echo $grouped['group1']['uid']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器