her66
her66

Reputation: 41

Display odd and even row data from mysql query next to each other with PHP

I use a mysql query to get the following data from games played between two teams:

| name  |score|
---------------
|John   |  7  |
|Danny  |  0  |
|John   |  7  |
|Peter  |  5  |

Then I use some PHP code (see below) to display the data as follows:

|Player 1|Score 1|Player 2|Score 2|
-----------------------------------
|John    |   7   |Danny   |   0   |
|John    |   7   |Peter   |   5   |

But I want:

|Player 1|  Score  |Player 2|
-----------------------------
|John    |  7 - 0  |Danny   |
|John    |  7 - 5  |Peter   |

The code I am using to display two rows from sql side-by-side with PHP (inspired from here) is:

// output data of each row
$i = 0;
while($row = $result->fetch_assoc()){
// Odd row opens
if (++$i % 2 != 0) echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['score']."</td>";

// Even row closes
if ($i % 2 == 0) echo "</tr>";
}

I am struggling for many days now but can't seem to find a way to get it right. If it might help I could provide the actual sql query and my complete Table structure as an image.

Any help greatly appreciated. Thanks!

Upvotes: 2

Views: 357

Answers (1)

Adlan Arif Zakaria
Adlan Arif Zakaria

Reputation: 1745

You can split those data into 2 separated arrays first.

// output data of each row
$list1 = [];
$list2 = [];

while($row = $result->fetch_assoc()){
    array_push($list1, [
        'name' => $row['name'],
        'score' => $row['score']
    ]);

    // Get next row
    $row = $result->fetch_assoc();

    array_push($list2, [
        'name' => $row['name'],
        'score' => $row['score']
    ]);
}

Then you can print them properly:

foreach($list1 as $i => $player) {
    echo "<td>".$player['name']."</td>";
    echo "<td>".$player['score']." - ".$list2[$i]['score']."</td>";
    echo "<td>".$list2[$i]['name']."</td>";
}

Upvotes: 1

Related Questions