Page 1 of 1

Array Table Display

Posted: Fri Feb 01, 2008 12:13 pm
by Johnlbuk
Hi,
I am trying to display a array as a table.

The code to create the array

Code: Select all

<?php $query = "SELECT name FROM table"; 
    $result=mysql_query($query);
    while($data = mysql_fetch_array($result)) {
 
$name = $data["name"];
$price= $data["price"];
    
$rowarray = array($name,$price);
    }
?>
I then want to display the results of the array in this following form

Column 1 Column 2
row1 Name Price
row2 Name Price
row3 Name Price
etc

Any shread of the light would be great.
Cheers,
John

Re: Array Table Display

Posted: Fri Feb 01, 2008 12:53 pm
by JAM
You could echo the contents in the while-loop directly instead of creating another array with the data, but...
Use a foreach() on $rowarray.

Re: Array Table Display

Posted: Sat Feb 02, 2008 2:24 am
by GuitarheadCA
$name = $data["name"];
$price= $data["price"];

$rowarray = array($name,$price);
It seems to me this round of assignments just makes things more complicated. Why not populate the table directly with the fetched array? it might look something like this:

Code: Select all

<?php 
$query = "SELECT name, price FROM table";
$result=mysql_query($query);
 
echo '<table>'
$i = 1;
while($data = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>row' . $i . '</td>';
echo '<td>' . $data['name'] . '</td>';
echo '<td>' . $data['price'] . '</td>';
echo '</tr>';
$i++;
}
?>
echo '</table>'

Re: Array Table Display

Posted: Sun Feb 03, 2008 3:24 am
by Johnlbuk
Yes. That would work using the fetch, but I need it to be in array as it is then going to be displayed on multiple pages. So I want to build the array and then, display it.


I am using this code to show the array now but it is only showing the name and then stopping so the price is not displayed. Any ideas?

Code: Select all

function show_array($array, $level, $sub){
    if (is_array($array) == 1){          // check if input is an array
       
    foreach($array as $key_val => $value) {
           $offset = "";
           if (is_array($value) == 1){   // array is multidimensional
           echo "<tr>";
           $offset = do_offset($level);
           echo $offset . "<td>" . $key_val . "</td>";
 
           show_array($value, $level+1, 1);
           }
           else{                        // (sub)array is not multidim
           if ($sub != 1){          // first entry for subarray
 
               $offset = do_offset($level);
           }
           $sub = 0;
           echo $offset . "<td>$value</td>"; 
 
           }
       } //foreach $array
    }  
    else{ // argument $array is not an array
        return;
    }
}