首页 > 解决方案 > 为同一对象分组元素

问题描述

这是具有不同元素的对象的简化数组(它是数据库的结果)。我正在尝试将每个人的类组合在一起,以便我可以在 html 表中显示它作为最终结果,我在 foreach 循环之后使用它:

echo'<td>'.$result->id_person.'</td>';
echo'<td>'.$result->id_class.'</td>';`  

我尝试使用 2 个 for 循环和 if 循环来解析 Array,但它没有按预期工作。请问有人可以帮我吗?

我想id_class为同一个人分组

Array
(
[0] => stdClass Object
    (
        [id_person] => 1
        [id_class] => 32
        
     )

[1] => stdClass Object
    (
        [id_person] => 5
        [id_class] => 32
     )

[2] => stdClass Object
    (
        [id_person] => 7
        [id_class] => 9
     )

[3] => stdClass Object
    (
        [id_person] => 7
        [id_class] => 40
        
     )

标签: phparraysobject

解决方案


像下面这样在循环中进行简单检查将确定当前事件与上次事件是针对同一个人的。

$id_person = null;
foreach($results as $result){
    if ( $id_person == $result->id_person ) {
        echo'<td>&nbsp;</td><td>'.$result->id_class.'</td>';`  
    } else {
        echo'<td>'.$result->id_person.'</td><td>'.$result->id_class.'</td>';`   
        $id_person = $result->id_person;
    }
}

这应该产生一个像这样的表。

1   32
5   32
7   9
    40

推荐阅读