Derfder
Derfder

Reputation: 3324

Adding values into array in while loop overriding old values

This is my code:

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(); ?>

But it outputs in var_dump only one winner and team not 15 from my database. How to fix it?

Upvotes: 1

Views: 549

Answers (2)

raidenace
raidenace

Reputation: 12826

You need some kind of unique match identifier for each match when constructing the array. Something like:

<?
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();
?>

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270607

For each iteration, append a new array with winner and team as its keys. The result will be a 2-dimensional array containing all your values.

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);

Otherwise, you are just overwriting the same two keys winner and team on every iteration.

Upvotes: 1

Related Questions