2

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!

1 Answer 1

1

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>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Works exactly as needed. You may wish to correct/edit the missing semicolumn at the end of the "$row = $result->fetch_assoc()" statement. It took me some hours to find out why it was not working initially.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.