简体   繁体   English

PHP关联数组到表

[英]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. 我正在尝试按升序对关联数组进行排序,然后将其传输到HTML表中,但目前我陷入了错误。 I looked for guidelines here on SO and followed instructions on some posts: 我在此处查找有关SO的指南,并按照一些帖子中的说明进行操作:

PHP display associative array in HTML table PHP在HTML表中显示关联数组

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() 错误是为foreach()提供了无效的参数

Because your $bib is only single array but you use two foreach to loop this array 因为$bib只是单个数组,但是您使用了两个foreach来循环该数组

At 2nd loop, your $row variable is a string, you can't use foreach for this type 在第二个循环中,您的$row变量是一个字符串,您不能为此类型使用foreach

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 $kLuke John MattMark$v10 30 2040

You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php 您可以在此处看到foreach示例: 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);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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