Как правильно отобразить заголовок таблицы и строки из файла JSON - PullRequest
0 голосов
/ 17 сентября 2018

Я пытаюсь выяснить, как отобразить файл JSON в пользовательскую таблицу HTML и сначала получить ключи объектов, затем значения и отобразить их в моей таблице.

Вот код, который я пытаюсь:

    <!-- table header -->
    <thead>
       <?php 
       // Load the file
       $jsonStr = file_get_contents("Users.json");
       // Decode the JSON data into a PHP array.
       $jsonObjs = json_decode($jsonStr, true);

       foreach($jsonObjs as $key => $value) {
         $obj = $jsonObjs[$i];
         echo '<th>'.$obj[$key].'</th>';
       } 

       echo '
       </thead><!-- ./ table header -->

       <tbody>
       <!-- table row -->
       <tr>';

       foreach($jsonObjs as $key => $value) {
          $obj = $jsonObjs[$i];
          echo '<td>'.$obj[$value].'</td>';
       }
   ?>
<td>
<a href="#a" class="btn btn-info btn-fill" onclick="showNotification('Object successfully edited!')"><i class="nc-icon nc-settings-90"></i> Edit</a>
&nbsp;&nbsp;&nbsp;
<a href="#a" class="btn btn-danger btn-fill" onclick="showDeleteModal()"><i class="nc-icon nc-simple-remove"></i> Delete</a>
</td>
</tr><!-- ./ table row -->

Вот мой Users.json файл:

[
    {
        "objID":"u7uSoWCPW8",
        "string":"bobby",
        "createdOn":"2018-09-17  08:08:30",
        "updatedOn":"2018-09-17 08:08:30",
        "number":111,
        "boolean":true,
        "array":["john","sarah"],
        "pointer2":{
            "type":"__pointer",
            "objID":"dfg56FdE",
            "className":"Users"
        }
    },
    {
        "objID":"rvLXpsN7Cb",
        "string":"bobby",
        "createdOn":"2018-09-17  09:03:30",
        "updatedOn":"2018-09-17 09:03:30",
        "number":111,
        "boolean":true,
        "array":["john","sarah"],
        "pointer2":{
            "type":"__pointer",
            "objID":"dfg56FdE",
            "className":"Users"
        }
    }
]

Когда я запускаю свою HTML-страницу с таблицей, я получаю только 2 кнопки в конце строки (иТолько 1 ряд).Что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 17 сентября 2018

Так же, как альтернатива.

Если вы Ajax файл на страницу,

fetch('Users.json').then(process);

вы можете сделать что-то вроде этого:

var tHead = document.getElementById("th"),
  tBody = document.getElementById("tb"),
  tr, td, text,
  thr = document.createElement("tr"); // this is the table header row
 
 // this whole thing goes away when you activate the fetch
 var data = [{ "objID": "u7uSoWCPW8", "string": "bobby", "createdOn": "2018-09-17 08:08:30", "updatedOn": "2018-09-17 08:08:30", "number": 111, "boolean": true, "array": ["john", "sarah"], "pointer2": { "type": "__pointer", "objID": "dfg56FdE", "className": "Users" } }, { "objID": "rvLXpsN7Cb", "string": "bobby", "createdOn": "2018-09-17 09:03:30", "updatedOn": "2018-09-17 09:03:30", "number": 111, "boolean": true, "array": ["john", "sarah"], "pointer2": { "type": "__pointer", "objID": "dfg56FdE", "className": "Users" } } ]
 
function process(data) {
  data.forEach(function(item, i) { // array
    tr = document.createElement("tr"); // create the row

    for (key in item) {
      if (i === 0) {  // save the THs from the first item
        th = document.createElement("th");
        th.innerHTML = key;
        thr.appendChild(th);
      }
      text = []; // this is for the array and object in the item
      if (typeof item[key] == "object") {
        if (Array.isArray(item[key])) {
          item[key].forEach(function(item2, j) { // Array forEach
            text.push(item2)
          });
        } else {
          for (key2 in item[key]) {
            text.push(key2 + ":" + item[key][key2]); // Object for..in
          }
        }
      } else {
        text.push(item[key]); // everything else
      }
      td = document.createElement("td");
      td.innerHTML = text.join("<br/>");
      tr.appendChild(td);
    }
    tBody.appendChild(tr);
  });
  tHead.appendChild(thr);
}

process(data); // to be replaced with fetch('Users.json').then(process);
td {
  border: 1px solid black;
}
<table>
  <thead id="th"></thead>
  <tbody id="tb"></tbody>
</table>
0 голосов
/ 17 сентября 2018

сначала создать заголовок таблицы

foreach($jsonObjs[0] as $key => $value) {
    echo '<th>'.$key.'</th>';
} 

создать тело

foreach($jsonObjs as $obj) {
    echo '<tr>';
    foreach($obj as $key => $value){
        echo '<td>'.$value.'</td>';
    }
    echo '</tr>';
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...