如果值已经被回​​显,则php foreach循环继续

时间:2014-09-18 21:16:44

标签: php joomla

我有一个foreach循环,如果值已经被回​​显,我需要添加一个continue。我无法找到正确的语法。循环:

foreach ($results as $result) {
   echo $result->date . "<br />"; 
}

但我需要添加一个继续,以便如果该值已经被回​​显,并且它在循环中再次出现则会被跳过。我无法完全理解if / continue语句。

思想,建议,想法?

3 个答案:

答案 0 :(得分:3)

如@JonathanKuhn在评论中所提到的 - 这是你如何运行该循环:

$already_echoed = array();
foreach ($results as $result) {
    if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
        echo $result->date . "<br />";   
    }
    $already_echoed[] = $result->date; //store all dates in an array to check against.
}

答案 1 :(得分:2)

$echoedArray = array();
foreach ($results as $result) {
    if (isset($echoedArray[$result->date])) {
        continue;
    }
    echo $result->date . "<br />";
    $echoedArray[$result->date] = true;
}

答案 2 :(得分:1)

    $alreadyOutput = array();
    foreach ($results as $result) {
       if(in_array($result->date, $alreadyOutput)){
           continue;
       }
       $alreadyOutput[] = $result->date; 
       echo $result->date . "<br />";
    }