PHP如果if语句中没有显示任何内容

Joh*_*ill 0 php arrays foreach if-statement

这是我的数组:

Array
(
    [0] => Array
        (
            [id] => 5
        )

    [1] => Array
        (
            [id] => 9
        )

    [2] => Array
        (
            [id] => 2
        )
Run Code Online (Sandbox Code Playgroud)

这是我的PHP代码:

<?php
foreach($results as $row) {
    if($row['id'] > 10) {
        echo $row['id'];
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

因为没有大于10的id,我希望它:

echo 'Nothing found';
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?谢谢.

Jef*_*eff 7

只需设置一个布尔标志:

$foundone=false;

foreach($results as $row) {
   if($row['id'] > 10) { 
       $foundone = true;
       echo $row['id'];
   }
}

if(!$foundone) {
  echo "Nothing found";
}
Run Code Online (Sandbox Code Playgroud)

替代方案:对数组进行排序(通过usort fe)并检查最高值:

usort($array, function ($a, $b) { return $a['id']>$b['id']; });
if ($array[count($array)-1]['id'])>10) {
   echo "found an id higher than 10!";
} else {
   echo "nothing found";
}
Run Code Online (Sandbox Code Playgroud)

但我怀疑这会更快和/或更容易阅读和维护.