0

我搜索了整个网络,或者我只是没有看到它。

我想做以下事情:

<?php

 function abc(){
   $sql = "SELECT * FROM table";
   $result = mysql_fetch_assoc($sql);
   $data = mysql_fetch_assoc($result);
}

?>

<? while(abc()) : ?>

   <?=article_title()?>
   <?=article_content()?>

<?=endwhile;?>

有人可以给我一个方向和/或例子吗?

非常感谢

4

2 回答 2

2

PHP 没有生成器/迭代器函数,所以你不能这样做。

但是,您可以返回一个数组并遍历该数组:

function abc() {
    // ...
    $rows = array();
    while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
    return $rows;
}

foreach(abc() as $row) {
    // do something
}

如果您调用的函数需要访问该行,请将其作为参数传递。使用全局变量会非常糟糕/讨厌

于 2012-04-23T17:54:11.197 回答
1

你试过做这样的事情吗?

<?php
function getData(){
    //get the data from the database
    //return an array where each component is an element found
}

$elems = getData();
foreach($elems as $e){
    doSomethingWith($e);
}
于 2012-04-23T17:58:41.793 回答