Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP display associative array in HTML table

Here is my associative array:

$req_data1[]=array(
    'depart1'=>$_REQUEST['to'],
    'd_time1'=>$d_time5,
    'stop'=>"",
    'leave_stop'=>"",
    'arrival1'=>$_REQUEST['from'],
    'a_time1'=>$end_time5,
    'price1'=>intval($final_price),
    'air_line'=>"xxxxx");

Here is my sorting algorithm:

foreach ($req_data as $key => $row) {
    $depart[$key]  = $row['depart'];
    $d_time[$key] = $row['d_time'];
    $stop[$key]  = $row['stop'];
    $leave_stop[$key] = $row['leave_stop'];
    $arrival[$key]  = $row['arrival'];
    $a_time[$key] = $row['a_time'];
    $price[$key] = $row['price'];
}

array_multisort($price,SORT_ASC, $req_data);

I am displaying the data after sorting:

foreach($req_data as $key=>$row) {
    echo "</br>";

    foreach($row as $key2=>$row2){
        echo $row2;
    }
}

My problem now is that I want to put that array into an HTML table but dont know how. This is my code which I tried so far but its not working:

$cols = 5; 

echo "<table border=\"5\" cellpadding=\"10\">"; 

for ($r=0; $r < count($row2); $r++) { 
    echo "<tr>"; 

    for ($c=0; $c<$cols; $c++) { 

        ?> <td> <?php $input[$r+$c] ?> </td> <?php 
        }

    echo "</tr>"; 
    $r += $c; 
}

echo "</table>";
?>

Could any one tell me what is wrong with my code, or how I can display this sorted data into a table? Thanks.

like image 779
Kashif Waheed Avatar asked Nov 24 '25 23:11

Kashif Waheed


2 Answers

Why not just modify the loop you already use to display the data?

echo "<table>";
foreach($req_data as $key=>$row) {
    echo "<tr>";
    foreach($row as $key2=>$row2){
        echo "<td>" . $row2 . "</td>";
    }
    echo "</tr>";
}
echo "</table>";
like image 156
Dan Grossman Avatar answered Nov 27 '25 13:11

Dan Grossman


$toOutput = '<table>';
$showHeader = true;
$memberData = $reportObj->getMemberData();
while($row = mysql_fetch_assoc($memberData))
{
    $toOutput .= '<tr>';

    //Outputs a header if nessicary
    if($showHeader)
    {
        $keys = array_keys($row);
        for($i=0;$i<count($keys);$i++)
        {
            $toOutput .= '<td>' . $keys[$i] . '</td>';
        }
        $toOutput .= '</tr><tr>';
        $showHeader = false;
    }

    //Outputs the row
    $values = array_values($row);
    for($i=0;$i<count($values);$i++)
    {
        $toOutput .= '<td>' . $values[$i] . '</td>';
    }

    $toOutput .= '</tr>';
}
$toOutput .= '</table>';

echo 'Test page';
echo $toOutput;

Sorry for the necro, but I was actually looking to see if there was a build-in function for this as I was writing this.

like image 29
Austin DeVinney Avatar answered Nov 27 '25 11:11

Austin DeVinney