Php Foreach计数器断开-列表到许多相同的行
以下是代码,此代码生成以下输出: 这个想法是每次床位数量改变时都有一个不同的标题Php Foreach计数器断开-列表到许多相同的行,php,arrays,foreach,Php,Arrays,Foreach,以下是代码,此代码生成以下输出: 这个想法是每次床位数量改变时都有一个不同的标题 $tableTop = '<table> ... <tbody>'; $tableBottom = '</tbody> </table>'; $last_bed = null; foreach ($unitsForSaleData as $row) { if($units_for_sale['beds'] == 0){ if ($last_bed
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if ($last_bed == null) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop
$tableTop='…';
$tableBottom='';
$last_bed=null;
foreach($unitsForSaleData作为$row){
如果($U待售单位['beds']==0){
如果($last_bed==null){
echo“出售工作室”;
echo$桌面;
$last_bed=$units_for_sale[“beds”];
}
}否则{
如果($units\u for_sale['beds']!==$last\u bed){
如果($last_bed!==null){//结束上一个表
回声$tableBottom;
}
echo“.$units”出售[“床”]。“卧室公寓出售”;
echo$tableTop;//启动新表
$last_bed=$units_for_sale[“beds”];
}
}
?>
...
用isset
而不是==null
解决了这个问题。下面是所有需要这样做的人的完整代码:
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if (!isset($last_bed)) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop
$tableTop='…';
$tableBottom='';
$last_bed=null;
foreach($unitsForSaleData作为$row){
如果($U待售单位['beds']==0){
如果(!isset($last_bed)){
echo“出售工作室”;
echo$桌面;
$last_bed=$units_for_sale[“beds”];
}
}否则{
如果($units\u for_sale['beds']!==$last\u bed){
如果($last_bed!==null){//结束上一个表
回声$tableBottom;
}
echo“.$units”出售[“床”]。“卧室公寓出售”;
echo$tableTop;//启动新表
$last_bed=$units_for_sale[“beds”];
}
}
?>
...
你能给我们一个你正在循环的数组的例子吗?你的意思是什么?我添加了一个更详细的代码。问题是第一个块中的每一项都有自己的表围绕着它。请看屏幕快照。我建议使用empty()而不是!isset(),因为它在更大范围的空值上返回TRUE。