我有一个从 URL 生成的数组。
$url = 'https://www.datastro.eu/api/explore/v2.1/catalog/datasets/orbits-for-current-comets-in-the-mpc-database/records?order_by=h%20ASC' ;
$data = file_get_contents($url);
$comets = json_decode($data, true);
if ($comets === null) {
die("Error decoding JSON data.");
}
//echo '<pre>'; print_r($comets); echo '</pre>';
我填充了一个表:
<table class="table table-dark table-striped display" id="myTable">
<thead>
<tr>
<th scope="col">designation_and_name</th>
<th scope="col">orbit_type</th>
...
</tr>
</thead>
<tbody>
<?php for ($i=0; $i<=$comete['total_count']; $i++) { ?>
<tr>
<th scope="row"><?php echo($comete['results'][$i]['designation_and_name']); ?></th>
<td><?php echo($comete['results'][$i]['orbit_type']); ?></td>
...
</tr>
<?php } ?>
</tbody>
</table>
到目前为止一切顺利,但是当我插入 DataTable 脚本时,表变为空。
<script>
new DataTable('#myTable');
</script>
请帮助我!我想对表格应用制表位,否则将无法管理。
API 仅返回总记录中的 10 条,并且由于您使用基于 total_count 值的 for 循环,当索引引用超出范围的行时,将返回 null 值(生成抑制的 PHP警告)并且相关的回显产生一个空值,因此您的表有一堆空行。由于 dataTables 默认按第一行升序排序,因此您会在顶部看到所有空行:表未清空,您会看到第一个空行。
以下是一些代码更改以确保这一点:
<?php
$url = 'https://www.datastro.eu/api/explore/v2.1/catalog/datasets/orbits-for-current-comets-in-the-mpc-database/records?order_by=h%20ASC' ;
$data = file_get_contents($url);
$comets = json_decode($data, true);
if ($comets === null) {
die("Error decoding JSON data.");
}
//--- Prints the total rows counter and the total rows really received
echo '<br>', 'Total rows:', $comets['total_count'], '<br>', 'Total received:', count($comets['results']), '<br><br>';
?>
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.datatables.net/2.0.3/css/dataTables.dataTables.css" rel="stylesheet">
</head>
<body>
<table class="table table-dark table-striped display" id="myTable">
<thead>
<tr>
<th scope="col">designation_and_name</th>
<th scope="col">orbit_type</th>
<th scope="col">node</th>
<th scope="col">e</th>
<th scope="col">h</th>
<th scope="col">g</th>
</tr>
</thead>
<tbody>
<!-- Using foreach we traverse the real rows received (here in the alternative syntax for greater readability) -->
<?php foreach ($comets['results'] as $row):?>
<tr>
<!-- php echo in shorthand format -->
<th scope="row"><?= $row['designation_and_name'] ?></th>
<td><?= $row['orbit_type'] ?></td>
<td><?= $row['node'] ?></td>
<td><?= $row['e'] ?></td>
<td><?= $row['h'] ?></td>
<td><?= $row['g'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
let dt = new DataTable('#myTable');
// prints in the browser's console the default order set by DataTables
console.log (dt.order());
});
</script>
</body>
</html>
我认为 API 需要授权才能接收所有行(检查此处)