在while循环中将值添加到数组中,覆盖旧值

时间:2012-10-11 18:04:32

标签: php arrays while-loop

这是我的代码:

if ( 0 < $matches->total() ) {
    while ( $matches->fetch() ) {
        ?>
            <?php $ma1_winner      = $matches->display( 'winner' ); ?>
            <?php $ma1_team_1      = $matches->display( 'team_1' ); ?> 
            <?php $matches_array_1['winner'] = $ma1_winner; ?>
                <?php $matches_array_1['team1'] = $ma1_team_1; ?>
            <?php
                    } // end of while loop
            } // end of if any exists
            ?>


            <?php var_dump($matches_array_1); ?>
            <?php die(); ?>

但它在var_dump中输出的只有一个获胜者而团队不是来自我的数据库的15个。如何解决?

2 个答案:

答案 0 :(得分:1)

对于每次迭代,添加一个以winnerteam为键的新数组。结果将是一个包含所有值的二维数组。

while ($matches->fetch() {
  // Append a new array via [] = array()
  // for every loop iteration
  $matches_array_1[] = array(
     'winner'=>$matches->display('winner'), 
     'team'=>$matches->display('team')
  );
}
var_dump($matches_array_1);

否则,您只是在每次迭代时覆盖相同的两个键winnerteam

答案 1 :(得分:1)

构造数组时,每个匹配都需要某种唯一匹配标识符。类似的东西:

<?
if ( 0 < $matches->total() ) 
{
    while ( $matches->fetch() ) 
    {
        $matches_array_1[$matches->display('match_id')]['winner'] = $matches->display( 'winner' );
        $matches_array_1[$matches->display('match_id')]['team1']  = $matches->display( 'team_1' );
    } // end of while loop
} // end of if any exists
var_dump($matches_array_1); 
die();
?>