b0or3ed
b0or3ed

Reputation: 13

Multidimentional array to HTML tables using PHP

I'm trying to display this array into a 3-column HTML tables using PHP:

[user] => Array (
 [0] => 024366c0a0d88ee4d2e3c8e479d8f8bb361c1908
 [1] => 1dfb9ba35f5995a8213f623ec3536947242c877d
 [2] => 1f2f182fde1f4bc8d2262639c51be73b5d8555b1
 [3] => 2219ffa1265576f56ccea846a5f0983391fe3a3a
 [4] => 517c3b6c008b582dcafb7cb60450abd19147e21a
)
[song] => Array (
 [0] => SOAKIMP12A8C130995
 [1] => SOAKIMP12A8C130995
 [2] => SOAKIMP12A8C130995
 [3] => SOAKIMP12A8C130995
 [4] => SOAKIMP12A8C130995
)
[rating] => Array (
 [0] => 100
 [1] => 100
 [2] => 100
 [3] => 100
 [4] => 100
)

So far I've tried this to display each row individually:

<table border="1px">
    <tr>
        <td><?php echo $array['user'][0] ?></td>
        <td><?php echo $array['song'][0] ?></td>
        <td><?php echo $array['rating'][0] ?></td>
    </tr>
</table>

And this but it became 5 column:

<?php foreach ($array as $row) {
        echo ('<tr>');
        echo ('<td>');
        echo (implode('</td><td>', $row));
        echo ('</td>');
        echo ('</tr>');
    } ?>

Context on how I need it to look like:

------------------------
|user   |song   |rating|
|024366c|SOAKIMP|100   |
|12424ta|SOAKIMP|100   |
|453e2bc|SOAKIMP|100   |
------------------------

Upvotes: 1

Views: 42

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94682

Using a foreach you can get the index of the array being processed $idx. You can then use that in the lines processing the other sub arrays

<table border="1px">
<?php 
foreach ($array['user'] as $idx => $row) : 
?>
    <tr>
        <td><?php echo $row ?></td>
        <td><?php echo $array['song'][$idx ] ?></td>
        <td><?php echo $array['rating'][$idx ] ?></td>
    </tr>
<?php 
endforeach;
?>
</table>

Warning This does need the 3 arrays to always be of the same length

Upvotes: 1

Related Questions