简体   繁体   中英

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

Because your $bib is only single array but you use two foreach to loop this array

At 2nd loop, your $row variable is a string, you can't use foreach for this type

Can you try that for single array ?

<?php
function format($data) {
    array_multisort($data, SORT_ASC);
    echo "<table>";
    foreach($data as $k => $v) {
        echo "<tr>";
        echo "<td>$k</td>";
        echo "<td>$v</td>";
        echo "</tr>";
    }
    echo "</table>";
}

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

?>

$k is Luke John Matt and Mark , $v is 10 30 20 and 40

You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php

Hope this helpful ^^

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

?>

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