Nested foreach()

前端 未结 4 2014
面向向阳花
面向向阳花 2021-01-08 00:56

I have the following array:

Array ( 
  [1] => Array ( 
    [spubid] => A00319 
    [sentered_by] => pubs_batchadd.php
    [sarticle] => Lateral m         


        
相关标签:
4条回答
  • 2021-01-08 01:14

    Just for fun. If you really want to avoid loops, try this:

    // 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";
    });
    0 讨论(0)
  • 2021-01-08 01:17

    Take a look at this

    0 讨论(0)
  • 2021-01-08 01:23

    If your problem is that you have the same author on multiple articles and thus getting output more than once, the simplest solution is to build an array of authors instead of outputting them right away.

    When you have an array of all the authors you've processed so far you can easily compare if this author is already in there or not.

    0 讨论(0)
  • 2021-01-08 01:35

    Why don't you do

    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";
    }
    
    0 讨论(0)
提交回复
热议问题