php - 如何循环遍历多维数组

时间:2014-08-10 20:00:31

标签: php arrays loops multidimensional-array foreach

我试图返回一个队列表以及队员中的队员。这是我的数组的缩短版本。

Array ( 
    [0] => Array ( 
        [team_id] => 1 
        [team_name] => Team1 
        [players] => Array ( 
             [0] => stdClass Object ( 
                 [n_name] => player1 ) 
             [1] => stdClass Object ( 
                 [n_name] => player2 )
     ) ) 
   [1] => Array ( 
        [team_id] => 2 
        [team_name] => Team2 
        [players] => Array ( 
             [0] => stdClass Object ( 
                 [n_name] => player3 ) 
             [1] => stdClass Object ( 
                 [n_name] => player4 )
     ) )
) 

我如何通过团队和玩家循环来获得类似的东西:

TEAM_ID: 1
TEAM_NAME: Team1
PLAYERS: player1, player2

TEAM_ID: 2
TEAM_NAME: Team2
PLAYERS: player3, player4

foreach中的foreach?

2 个答案:

答案 0 :(得分:2)

foreach($teams as $team) {
    echo 'TEAM_ID: ' . $team['team_id'] . '<br />';
    echo 'TEAM_NAME: ' . $team['team_name'] . '<br />';
    echo 'PLAYERS: ';

    for($i = 0; $i < count($team['players']); $i++) {
        echo $team['players'][$i]->n_name;

        if($i < count($team['players']) - 1) {
            echo ', ';
        }
    }

    echo '<br /><br/>';
}

答案 1 :(得分:0)

正确的假设。 foreach中的foreach。

Foreach($array as $value){
   //$value is now the inside array
   Foreach($value as $value2){
      //$value2 is the value of each variable of inside array
  }
}

在第一个foreach中使用回声来表达团队名称。在嵌套的foreach中表达玩家信息。