【发布时间】:2010-11-18 10:55:55
【问题描述】:
我有以下数组:
Array (
[1] => Array (
[spubid] => A00319
[sentered_by] => pubs_batchadd.php
[sarticle] => Lateral mixing of the waters of the Orinoco, Atabapo
[spublication] => Acta Cientifica Venezolana
[stags] => acta,confluence,orinoco,rivers,venezuela,waters
[authors] => Array (
[1] => Array (
[stype] => Author
[iorder] => 1
[sfirst] => A
[slast] => Andersen )
[2] => Array (
[stype] => Author
[iorder] => 2
[sfirst] => S.
[slast] => Johnson )
[3] => Array (
[stype] => Author
[iorder] => 3
[sfirst] => J.
[slast] => Doe )
)
)
)
我正在使用嵌套的 foreach() 遍历外部数组中的元素,但是在吐出作者列表时我遇到了问题。即由于疯狂的 foreach() 嵌套而导致每个输出多次(多次)的问题。在这个例子中,有什么比嵌套 foreach() 循环更好的方法?
更新(有解决方案)
这是我确定的循环,有点乱(恕我直言)但它有效:
$sauthors = NULL;
$stitle = NULL;
foreach($apubs as $apub)
{
$stitle = $apub['sarticle'];
foreach($apub as $svar=>$sval)
{
if($svar === "authors")
{
foreach($sval as $apeople)
{
$sauthors .= $apeople['slast'].", ".$apeople['sfirst']."; ";
}
}
}
echo "$sauthors<br />\n$stitle<br />\n";
}
【问题讨论】:
-
听起来不错,也许你应该发布你的循环代码?
-
默认情况下,嵌套循环并不是一件坏事。让我们看看一些代码。我的第一个疯狂猜测是你在内部循环中覆盖了外部循环中的一个变量:)
-
发布您的循环代码。嵌套 foreach 很好(使用 assoc 数组可以帮助您调试)