我很难从数组中获取正确的数据。我写了一个嵌套的foreach循环,但内部循环抛出了“为foreach()提供的”无效参数“错误。有人能帮我解决这个问题吗?谢谢。如何写一个会产生我想要的结果的foreach
foreach($row as $val)
{
echo $val['title'].'<br>';
echo $val['author'].'<br>';
echo $val['post'].'<br>';
echo $val['entry_date'].'<br>';
echo $val['comments'].'<br>';
foreach($val as $val2)
{
echo $val['comments'].'<br>';
}
}
Array
(
[title] => First Blog
[author] => Administrator
[post] => Testing entry number one
[entry_date] => Fri, 23 Oct 2009
[comments] => Array
(
[0] => Array
(
[commenter] => Sally Anderson
[comments] => comment 1 post 1
[comment_date] => October 24th, 2009 at 5:24 AM
)
[1] => Array
(
[commenter] => Mike Jones
[comments] => comment 2 post 1
[comment_date] => October 24th, 2009 at 5:21 AM
)
)
)
Array
(
[title] => Second Blog
[author] => Administrator
[post] => Testing entry number two
[entry_date] => Sat, 24 Oct 2009
[comments] => Array
(
[0] => Array
(
[commenter] => Sally Anderson
[comments] => comment 1 post 2
[comment_date] => October 24th, 2009 at 5:21 AM
)
[1] => Array
(
[commenter] => Mike Jones
[comments] => comment 2 post 2
[comment_date] => October 24th, 2009 at 5:21 AM
)
)
)
嗨Cletus,感谢您的帮助。我试过这个,但我仍然收到错误。我收到价值回声,但错误仍然出现在我的日志中。有任何想法吗? – Jack 2009-10-25 04:41:17
Cletus,谢谢。你的解决方案有效,但我不知道为什么......谢谢。我也会研究heredoc语法。 – Jack 2009-10-25 04:52:12
@jack - 拼出foreach .... foreach(item in)$ collection(as)$ singular(do)等等。当你到达嵌套数组时,你试图把它看作单数,而它是另一个集合!该集合($ row [注释]在你的情况)需要传递给嵌套循环; foreach(item in)$ comments_collection(as)$ comment(do).... – deau 2009-10-25 05:00:14