繁体   English   中英

基于字段的PHP SQL循环结果

[英]PHP SQL Loop results based on field

我正在创建一个动态记录集,在其中填充几个用于选择所有已记录记录的查询的值。

接下来,我需要循环并将结果分组,但是不确定如何按查询中使用的值分组。

参考查询:

SELECT fldItem, fldDescription, fldRank,fldType FROM tableName
WHERE fldType IN (33, 34, 36) ORDER BY fldRank

值33,34和36将动态传递给查询。 然后,我的目标是要有一个循环/重复区域,该区域可以分组显示,并且所有结果共享相同的fldType

结果应如下所示:

item1, description1, rank1, type33
item2, description2, rank2, type33
item3, description3, rank5, type33
item4, description4, rank6, type33
item5, description5, rank8, type33

--------

item6, descriptionv, rank1, type34
item7, descriptionw, rank2, type34
item8, descriptionx, rank3, type34
item9, descriptiony, rank4, type34
item10, descriptionz, rank5, type34

--------

item11, descriptionA, rank2, type36
item12, descriptionB, rank3, type36

使用do / while循环会显示所有要显示的项目,但不会进行任何分组。 是ForEach循环解决方案吗?

如果要在报表输出中讨论视觉分组,则需要跟踪每次循环迭代的值,然后在检测到更改时发出视觉中断。 像这样:

$last_type = null;
foreach ($records as $record) {
    if ($last_type !== null && $last_type != $record->fldType) {
        echo '<whatever your visual cue is>';
        $last_type = $record->fldType;
    }
}

另外,请确保您执行以下操作:

ORDER BY fldType, fldRank
SELECT fldItem, fldDescription, fldRank,fldType FROM tableName
WHERE fldType IN (33, 34, 36) ORDER BY fldType, fldRank

这将首先按fldType分组,然后按fldRank分组。 在您的PHP代码中,只需记住最后一个fldType,并在更改时添加一个新组即可。 现在将所有fldTypes组合在一起,因此您可以按顺序循环搜索结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM