Search code examples
phpmultidimensional-arrayphpmyadmindynamic-data

php dynamic table display


I have a returned multi dimensional array from my DB, looking something like this

   $prices = array();

    /*some SQL coding */
print_r($prices);
        Array
    (
          [0]
              [id] => 1
              [title] => XT1 Comp
              [young] => 50
              [mid] => 50
              [old] => 120
          [1]
              [id] => 2
              [title] => HH3 Enginee
              [young] => 150
              [mid] => 170
              [old] => 220
    )

So far so good. But how best to print this as a dynamic table ? Am a little stuck and any hint is greatly aprpeciated

I hope someone can help. I am hoping for a outpus like this:

id | title     | young| mid| old
1  |  XT1 Comp | 50   | 50 | 120
and so one for each row / array index or line

Kind regards Alex

EDIT -> this is how i get them.

$result_array = array();
        while($line = mysql_fetch_array($result, MYSQL_ASSOC))
            {
            $result_array[] = $line;
        }

        return $result_array

Solution

  • You can use a php foreach to output each of the items in $prices:

    <?php
    function queryResultAsTable($results) {
        if(count($results) == 0) {
            echo '<em>No rows returned</em>';
        } else {
            echo '<table><thead><tr><th>'.implode('</th><th>', array_keys(reset($results))).'</th></tr></thead><tbody>'."\n";
    
            foreach($results as $result) {
                echo '<tr><td>'.implode('</td><td>', array_values($result)).'</td></tr>'."\n";
            }
    
            echo '</tbody></table>';
        }
    }
    
    queryResultAsTable($prices);