将平面数组转换为按类别分组的数组 [英] Converting flat array into an array grouped by categories

查看:84
本文介绍了将平面数组转换为按类别分组的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据库表:

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

但是我需要将这些数据放在一个数组中,该数组按类别将它们的group分组.

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
                )

        )

)

我已经编写了一个foreach循环来执行此操作,但是我遇到了问题.

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.

我当时想,在循环之后,我可以将最后一行添加到新数组中,但是如果最后一行具有不同的组,我认为这可能会引起问题,我宁愿将解决方案内置到foreach中循环.

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?

我也很想知道我可以对当前代码进行哪些改进,但这对于codereview可能是一个更好的问题.

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.

我的循环:

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

推荐答案

请执行以下操作:

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

希望有帮助!

为了进一步证明该循环,您可以将分组值追加更改为以下内容:

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']

这篇关于将平面数组转换为按类别分组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆