php - 为同一对象分组元素
问题描述
这是具有不同元素的对象的简化数组(它是数据库的结果)。我正在尝试将每个人的类组合在一起,以便我可以在 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
)
解决方案
像下面这样在循环中进行简单检查将确定当前事件与上次事件是针对同一个人的。
$id_person = null;
foreach($results as $result){
if ( $id_person == $result->id_person ) {
echo'<td> </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
推荐阅读
- walmart-api - Walmart IO API:未订阅服务名称
- typescript - 打字稿联合类型到单个映射类型
- chromecast - 如何在基于网络的发件人上接收来自 Google Cast Receiver 的消息?
- python - 如何重塑测试数据框,使维度与训练和预测工作中使用的维度相同?
- python - 使用 Imagemagik 将未嵌入字体的 pdf 转换为 png
- android - 如何在 OpenGL 图像查看器中跟踪“亮点”
- react-native - 尝试注册 RCTBridgeModule 类 RCTWebSocketModule
- python - 我的dqn不好用:奖励不变,损失不断增加
- mysql - MySql 不使用空间索引
- xero-api - 我刚刚更新了我的 Xero 私有应用程序的 Oauth 安全证书,现在我收到一个“错误:1Curl 错误:”