我很难从数组中获取正确的数据。我编写了一个嵌套的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
)
)
)
答案 0 :(得分:3)
假设$rows
是问题底部的结构(数组数组),那么:
foreach ($rows as $row) {
echo <<<END
$row[title]<br>
$row[author]<br>
$row[post]<br>
$row[entry_date]<br>
END;
foreach ($row['comments'] as $comment) {
echo <<<END
$comment[comments]<br>
$comment[commentor]<br>
$comment[comment_date]<br>
END;
}
}
我强烈建议您选择有意义的名称(例如$comment
和$row
),而不是像$val
和$val2
那样无意义的名称,因为这些名称只会引起混淆。< / p>
此外,我在修订版中使用了heredoc syntax因为我倾向于认为可以使事情更具可读性,但这是可选的。一个更好的选择可能是:
<?php foreach ($rows as $row): ?>
<?php echo $row['title'] ?><br>
<?php echo $row['post'] ?><br>
<?php echo $row['entry_date'] ?><br>
<?php foreach ($row['comments'] as $comment): ?>
<?php echo $comment['comments'] ?><br>
<?php echo $comment['commentor'] ?><br>
<?php echo $comment['comment_date'] ?><br>
<?php endforeach; ?>
<?php endforeach; ?>
如果您散布了大量HTML,这可能很有用。以上内容切换为使用alternative control structures,这是可选的,但在此类代码中通常被认为更具可读性。
最后,你可以PHP short tags,有些人不喜欢(因为它们可能被禁用或与XML处理指令接口)但我通常更喜欢:
<? foreach ($rows as $row): ?>
<?= $row['title'] ?><br>
<?= $row['post'] ?><br>
<?= $row['entry_date'] ?><br>
<? foreach ($row['comments'] as $comment): ?>
<?= $comment['comments'] ?><br>
<?= $comment['commentor'] ?><br>
<?= $comment['comment_date'] ?><br>
<? endforeach; ?>
<? endforeach; ?>
答案 1 :(得分:0)
变化
foreach($val as $val2)
{
echo $val['comments'].'<br>';
}
到
foreach($val['comments'] as $val2)
{
echo $val2['comments'].'<br>';
}