xan xan - 4 months ago 18
HTML Question

PHP Associative Array To Table

I am trying to sort an associative array in ascending in order and then transfer it to a HTML table and I am currently stumped at an error. I looked for guidelines here on SO and followed instructions on some posts:

PHP display associative array in HTML table

But still no luck, here is my attempt:

<?php
function format($g){

array_multisort($g, SORT_ASC);
echo "<table>";
foreach($g as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>


My debugger is telling me there is an error at my for each loop but I don't see how it is wrong unless there is some syntax error that I am not seeing? The error is saying Invalid argument supplied for foreach()

Answer

You can try this

<?php

function format($data){
    array_multisort($data, SORT_ASC);
    echo "<table>";
    foreach($data as $key => $row) {
        echo "<tr>";
            echo "<td>" . $key . "</td>";
            echo "<td>" . $row . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}

$bib = array(
    "Luke"=>"10", 
    "John"=>"30",
    "Matt"=>"20",
    "Mark"=>"40"
);

format($bib);

?>