嵌套的foreach()

时间:2009-08-10 22:12:38

标签: php arrays loops foreach

我有以下数组:

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";
}

4 个答案:

答案 0 :(得分:8)

你为什么不这样做

foreach($apubs as $apub) {
  $sauthors = '';
  $stitle = $apub['sarticle'];
  foreach($apub['authors'] as $author) {
    $sauthors .= $author['slast'].", ".$author['sfirst']."; ";
  }

  echo "$sauthors<br />\n$stitle<br />\n";
}

答案 1 :(得分:4)

只是为了好玩。如果确实想要避免循环,请尝试以下方法:

// Pre PHP 5.3:

function cb2($e)
{
    return $e['slast'] . ', ' . $e['sfirst'];
}

function cb1($e)
{
    $authors = array_map('cb2', $e['authors']);
    echo implode('; ', $authors) . ":<br />\n" . $e['sarticle'] . "<br />\n";
}

array_walk($data, 'cb1');



// PHP 5.3 (untested):

array_walk($data, function($e)
{
    $authors = array_map(function($e)
    {
        return $e['slast'] . ', ' . $e['sfirst'];
    },
    $e['authors']);

    echo implode('; ', $authors) . ":<br />\n" . $e['sarticle'] . "<br />\n";
});

答案 2 :(得分:3)

如果您的问题是您在多篇文章中拥有相同的作者并因此获得多次输出,那么最简单的解决方案是构建一组作者而不是立即输出。

如果您拥有目前已处理过的所有作者的数组,则可以轻松比较该作者是否已经在此处。

答案 3 :(得分:1)

选择look at this