简体   繁体   中英

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

use a loop:

foreach( $prices as $row ) {
    echo '|' . $row['id'] . '|' . $row['title'] . '|' . $row['young'] . '|';
    echo '|' . $row['mid'] . '|' . $row['old'] . '|';
}

It will go through each row and allow you to access each column value.

EDIT:

If you are using mysql_query(); to get the results then after you use it use the following:

while( $row = mysql_fetch_assoc( $query_result ) ) {
    // Same echo stuff here
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM