1

我需要将数组从 m.php 传回 index.php 并循环打印每一行,但我找不到方法怎么做?任何建议将不胜感激。

下面的代码我在 m.php 中使用 return $rows 但 index.php 无法得到它..

索引.php

<?php
require 'm.php';

$select_news = new select_news();
$select_news->select_3();
print_r($rows);
foreach ($rows as $row){
?>
<div><?=$row['id']?></div>
...
<?php
}
?>

m.php

class select_news{
    public function select_3(){
        global $db;
        $sth = $db->prepare('SELECT * FROM news ORDER BY id DESC LIMIT 3');
        $sth->execute();
        $rows = $sth->fetchAll();
            return $rows;
    }
}
4

2 回答 2

1

只需将该函数调用的值分配给一个变量……</p>

$select_news = new select_news();
$rows = $select_news->select_3();
print_r($rows);
foreach ($rows as $row){
?>
<div><?=$row['id']?></div>
...
<?php
}
?>
于 2013-10-13T03:50:42.947 回答
0

要将其转换为数组(如果我正确阅读了问题),您可以将其放在foreach语句上方:

$rows = unserialize(serialize(json_decode(json_encode((array) $rows), 1)));
于 2013-10-13T03:52:34.917 回答