简体   繁体   中英

PHP Parsing JSON to HTML Table multi dimensional arrays

I have the following JSON Data:

{
  "tables": [
    {
      "name": "PrimaryResult",
      "columns": [
        {
          "name": "TimeGenerated",
          "type": "datetime"
        },
        {
          "name": "Computer",
          "type": "string"
        }
      ],
      "rows": [
        [
          "2022-12-03T21:58:48.519866Z",
          "DESKTOP-KAFCPRF"
        ],
        [
          "2022-12-03T21:58:48.5198773Z",
          "DESKTOP-KAFCPRF"
        ]
      ]
    }
  ]
}

I'm using this to and trying to find a way to parse the columns as tables headers(TH) and the row data as(TR).

This is what I have:

  $jsonObjs = json_decode($data, true);
  echo "<pre>" . var_dump($jsonObjs) . "</pre>";
  foreach($jsonObjs as $a){
      foreach($a[0] as $b) {
        foreach($b[1] as $key => $value){
          echo $key . " : " . $value . "<br />";
        }
      }
  }

but my results are coming up like:

name : Computer
type : string
0 : 2022-12-03T21:58:48.5198773Z
1 : DESKTOP-KAFCPRF

Here is a loop that will go through the columns and rows. From here it's fairly simple to adjust the logic for building a table. If you need any further help, let me know.

foreach($jsonObjs["tables"] as $a)
  {
    // Columns
    foreach($a["columns"] as $key => $value)
    {
        $cName = $value["name"];
        $cType = $value["type"];
        
        echo("Column name is: ".$cName);
        echo("Column type is: ".$cType);
    }
    
    // Rows:
    foreach($a["rows"] as $key => $value)
    {
        $rValue1 = $value[0];
        $rValue2 = $value[1];
        
        echo("Row: " . $rValue1 . " | " . $rValue2);
    }
  }

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