0

I have a JSON file in this format I want to data display in the table using for loops and for each loop what can I do?

[{"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"}}]

i want to display in table through loop but i have problem how can i display all data thrugh using loops

    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>";
           }
faizan
  • 7
  • 3
  • Right now this question does not contain enough detail on what goes wrong / nor a sufficient code sample to tell. At the very least enable `error_reporting` before rushing to post a question. If unsure why you need `$data["fertilizer"]["prop*"]` please look at the duplicate. Also read up on array key quoting. – mario Jun 12 '18 at 10:51

1 Answers1

0

You are on the right way! First of all, json is a plain string in PHP. You need to decode it first using: json_decode(); For example:

$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>";
}
Jeroen
  • 147
  • 1
  • 12