在php中循环数组查找值停止循环和echo头

时间:2016-11-03 02:35:49

标签: php arrays json

foreach($resorts as $askiarea)
{

    $askiarea = (array) $askiarea;

    $askiarea['ReportType'] = $askiarea['resortStatus'];

    $flag=1;


    if (($askiarea['ReportType'] ==6) || ($askiarea['ReportType'] =="6"))
    {

        if($flag ==1)

    echo '<tr><th colspan="6" text-align="left"><div class="region-headline">Opening Soon For Snow Sports</div></th></tr>';}

    $flag = 0;



 }

每次尝试使用ReportType的值后,只需要回显一次标题,我会得到多个标题。

4 个答案:

答案 0 :(得分:0)

请添加大括号:

if($flag ==1) {

    echo '<tr><th colspan="6" text-align="left"><div class="region-headline">Opening Soon For Snow Sports</div></th></tr>';}

    $flag = 0;
}

答案 1 :(得分:0)

使用break语句。

foreach($resorts as $askiarea) {
    $askiarea = (array) $askiarea;
    $askiarea['ReportType'] = $askiarea['resortStatus'];
    if (($askiarea['ReportType'] ==6) || ($askiarea['ReportType'] == "6")) {
        echo '<tr><th colspan="6" text-align="left"><div class="region-headline">Opening Soon For Snow Sports</div></th></tr>';}
        break;
    }
}

有关休息here

的更多信息

答案 2 :(得分:0)

在检查ReportType之前,您在每次迭代中设置$flag = 1,因此当然会在每次迭代中打印标题。 $flag = 0没有在那里做任何事情。

在foreach循环之前设置$flag = 1,它将起作用。

答案 3 :(得分:0)

有点不确定你的阵列开始时的样子,但这是一个非常简单的例子:

<?php
$resorts = [0=>['ReportType'=>6],1=>['ReportType'=>6],2=>['ReportType'=>"6"]];

for ($c = 0; $c < count($resorts); $c++) {
    if ($resorts[$c]['ReportType'] == 6) {
        echo '<tr><th colspan="6" text-align="left"><div class="region-headline">Opening Soon For Snow Sports</div></th></tr>';
        break;
    }
} 
?>

它计算原始数组(我假设它是一个多维数组?)并根据它重复该值,如果找到则中断。 PHP在int和字符串之间没有区别,因此无需检查== 6== "6"

相关问题