如何使循环在 PHP 代码中脱离函数


how make loop work out of function in php code?

 <?php function getnews()
{
global $db;
$news=$db->query("select * from news order by news_id desc");
$row=$news->fetch_object();
return $row;
}?>

'

foreach (getnews() as $result)
 { 
   echo $result->news_title . "<br>";
 }
?>

但对于每个都不工作功能不足

任何帮助

您的getnews()函数只会从数据库中返回一行,即使您的查询将获取所有行。也许考虑 getnews() 函数中的一个循环,该循环依次返回每个循环,也许使用生成器,以便您可以在foreach循环中使用它们

function getnews() {
    global $db;
    $news=$db->query("select * from news order by news_id desc");
    while ($row=$news->fetch_object()) {
        yield $row;
    }
}
foreach (getnews() as $result) { 
   echo $result->news_title . "<br>";
}

虽然使用生成器确实需要 PHP>= 5.5

如果您使用的是早期版本的 PHP,那么在 getnews() 中构建一个数组并返回该数组,但它的效率不高:

function getnews() {
    global $db;
    $news=$db->query("select * from news order by news_id desc");
    $items = array();
    while ($row=$news->fetch_object()) {
        $items[] = $row;
    }
    return $items;
}
foreach (getnews() as $result) { 
   echo $result->news_title . "<br>";
}