[英]How to group items in while loop?
I am trying to group my output from my while loop, in PHP. 我试图在PHP中将我的while循环中的输出分组。
What I am trying to achieve, is I want each "box" with the same ' exposure
' to be grouped together, then whenever a new box, with a new ' exposure
' comes, a line break should appear, and the next group of exposure should be grouped. 我要实现的目标是,要将具有相同“
exposure
”的每个“框”分组在一起,然后每当一个带有新“ exposure
”的新框出现时,就会出现换行符,而下一组暴露应分组。
Currently, I have this PHP code: 目前,我有以下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'];
}
}
The above code, will just print them out like this: 上面的代码将像这样将它们打印出来:
https://docs.google.com/file/d/0Bw9EQNU6ms6jUXVyY1pndVlpY2c/edit?usp=drivesdk https://docs.google.com/file/d/0Bw9EQNU6ms6jUXVyY1pndVlpY2c/edit?usp=drivesdk
Although, what I want is like this: 虽然,我想要的是这样的:
https://docs.google.com/file/d/0Bw9EQNU6ms6jU0JYaDlHWEZsN1k/edit?usp=drivesdk https://docs.google.com/file/d/0Bw9EQNU6ms6jU0JYaDlHWEZsN1k/edit?usp=drivesdk
How can I achieve this? 我该如何实现?
I would make an array with all the 'exposures'. 我会用所有“曝光”制作一个数组。
$dataArray = array();
foreach ($result as $value){
$dataArray[$value['exposure']][] = $value;
}
This will result in an array ($dataArray) with all your exposure catagories in their respective index. 这将导致一个数组($ dataArray),其中所有曝光类别均位于各自的索引中。
Now you can loop through each of your 'exposures': 现在,您可以遍历每个“曝光”:
foreach ($dataArray as $exposure => $value){
echo 'Exposure: '.$exposure.'<br/>';
foreach ($value as $item){
// Any item information here.
}
echo '<hr>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.