0

我有以下代码:

$res = $db->getArticles($db);
$hey = print_r($res, TRUE);
echo $hey['0'];

这是代码$db->getArticles

public function getArticles() {
    $array = array();
    try {
        $sth = $this->db->prepare("SELECT * FROM posts ORDER BY id");
        $sth->execute();
        foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $array[] = $row;
        }
        return $array;
    } catch (Exception $e) {

    }
}

逻辑是该函数查询数据库并将所有内容放入数组中。表中的行数总是很低,所以性能不是问题。

以下是上面第一个代码片段的输出:

echo $hey['0']; // prints "A" (without the quotes).
echo $hey['1']; // prints "r"
echo $hey['2']; // prints "r"
echo $hey['3']; // prints "a"
echo $hey['4']; // prints "y"

如您所见,它拼出了单词“Array”。

echo $hey打印以下内容:

Array ( [0] => Array ( [id] => 1 [author] => 0 [content] => This Is a Test [publication_date] => 1380380992 ) )

我的最终目标是将每个单独的值存储到一个变量中并对其进行处理。这一切都发生在一个在数组上运行的 for 循环中,因此我可以从每一行获取信息。

我究竟做错了什么?

4

2 回答 2

1
$hey = print_r($res, TRUE);

这将返回一个给出数组信息的字符串$res。如果您回显它,您应该期望看到与显示的内容相同的内容print_r($res);,如您所展示的。$res已经是您的查询数据的数组,因此请对其进行循环。

foreach($res as $row) {  //row loop
  foreach($row as $col) {  //column loop
    //do something
  }
}
于 2013-09-30T14:53:22.237 回答
0
$array = array( array( ID => 1, 
                  author => 0,
                  content => "This Is a Test",
          publication_date => 1380380992
                )
         );



echo $array['0']['author'];

这对我有用...

只需回echo $array['0']['author'];显并用您需要的字段替换作者即可。

于 2013-09-30T14:45:38.970 回答