我正在尝试将我的输出从我的while循环中分组,在PHP中。
我想要实现的目标是,我想将每个“盒子”与相同的“exposure
”组合在一起,然后每当有新的“exposure
”新盒子出现时,应该出现换行符,并且应该对下一组曝光进行分组。
目前,我有这个PHP代码:
//Select from advertisements.
global $dbh;
$r = $dbh->prepare("
SELECT * FROM advertisements
WHERE exposure!='0'
AND `status`='2'
AND (clicks_left_micro>0
OR clicks_left_mini>0
OR clicks_left_standard>0
OR clicks_left_extended>0
OR fixed='1')
ORDER BY exposure DESC, fixed DESC");
$r->execute();
$last = null;
while($row=$r->fetch(PDO::FETCH_ASSOC)){
$exposure = $row['exposure'];
switch ($exposure) {
case 1:
$type = "";
break;
case 2:
$type = "ads-orange";
break;
case 3:
$type = "ads-green";
break;
case 4:
$type = "ads-blue";
break;
}
if ($row['token'] != $last) {
echo '
<a href="#">
<div class="col-xs-4 ads-box '.$type.'">
<div class="title">'.$row['title'].'</div>
<div class="content">'.$row['description'].'</div>
</div>
</a>
';
$last = $row['token'];
}
}
上面的代码,只会将它们打印出来:
https://docs.google.com/file/d/0Bw9EQNU6ms6jUXVyY1pndVlpY2c/edit?usp=drivesdk
虽然,我想要的是这样的:
https://docs.google.com/file/d/0Bw9EQNU6ms6jU0JYaDlHWEZsN1k/edit?usp=drivesdk
我怎样才能做到这一点?
答案 0 :(得分:3)
我会制作一个包含所有'曝光'的数组。
$dataArray = array();
foreach ($result as $value){
$dataArray[$value['exposure']][] = $value;
}
这将产生一个数组($ dataArray),其中包含各自索引中的所有曝光类别。
现在你可以遍历每个'曝光':
foreach ($dataArray as $exposure => $value){
echo 'Exposure: '.$exposure.'<br/>';
foreach ($value as $item){
// Any item information here.
}
echo '<hr>';
}