我有这种格式的json文件

时间:2018-06-12 10:42:14

标签: php json

我有一个这种格式的JSON文件我想在表格中使用for循环和每个循环显示数据我该怎么办?

[{"fertilizer":
{"pg1":"-21.259515860749435","pg2":"24.741169305724725","lastyearlastmonth":"764.119","currentmonth":"601.671","currentyearytd":"5735.1","lastyearytd":"4597.6","pname":"Urea","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"-20.53085432388131","pg2":"9.258986807905458","lastyearlastmonth":"631.435","currentmonth":"501.796","currentyearytd":"2227.9","lastyearytd":"2039.1","pname":"DAP","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"67.37546062508531","pg2":"51.07126222636238","lastyearlastmonth":"36.635","currentmonth":"61.318","currentyearytd":"648.7","lastyearytd":"429.4","pname":"CAN","mmonth":"11","period":"11","myear":"2017"}}]

我希望通过循环显示在表中但我有问题如何使用循环显示所有数据

    foreach ($data as $nt) 
        {

           echo "<tr class='{$dispval} {$boldrow}' >";
           echo "<td>{$nt[pname]}</td>";
           echo "<td class='txtright'>" . number_format($nt[lastyearlastmonth],1) . " </td>";
           echo "<td class='txtright'>" . number_format($nt[currentmonth],1) . " </td>";
           echo "<td class='txtright'>" . number_format($nt[pg1],1) . " </td>";
           echo "<td class='txtright'>" . number_format($nt[lastyearytd],1) . " </td>";
           echo "<td class='txtright' >" . number_format($nt[currentyearytd],1) . " </td>";
           echo "<td class='txtright'>" . number_format($nt[pg2],1) . " </td>";

           echo "</tr>";
           }

1 个答案:

答案 0 :(得分:0)

你是正确的方式! 首先,json是PHP中的普通字符串。您需要先使用以下代码对其进行解码:json_decode(); 例如:

$items = json_decode('your json string here');
foreach($items as $item) {
  echo "<tr>";
  echo    "<td>".$item->fertilizer->pg1."</td>";
  echo    "<td>".$item->fertilizer->pg2."</td>";
  // etc
  echo "</tr>";
}