如何从api数据创建表格

问题描述:

我一直在研究这一段时间,而且我可能会让它变得更加困难。任何共享的知识将非常感激。 我的代码使用API​​调用数据,我能够将其显示为有序列表,但我希望使用表格格式使其更易于表现。 理想情况下,我的结果按日显示。 下面是我创建至今,但目前不输出任何东西:如何从api数据创建表格

echo "<table>"; 
echo "<tr>"; 
echo "<th>Date</th>"; 
echo "<th>Number of Asteroids</th>"; 
echo "</tr>"; 

echo "<tr>"; 
foreach ($near_earth_object->close_approach_data as $close_approach) { 

      echo "<td>" . $close_approach->close_approach_date . "</td>"; 

foreach ($data->near_earth_objects as $date => $count) { 

    echo"<td>" . sizeof($count) . "</td></tr>"; 

} 
} 

echo "<tr>";  
echo "<th>Asteroid Name</th>"; 
echo "<th>Asteroid Size</th>"; 
echo "<th>Velocity</th>"; 
echo "<th>Passing Earth By</th>"; 
echo "</tr>"; 

echo "<tr>"; 
    foreach ($data->near_earth_objects->$date as $near_earth_object) { 
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>"; 
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>"; 
    } 

foreach ($near_earth_object->close_approach_data as $close_approach) { 
echo "<td>" . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "</td><td>". $close_approach->miss_distance->kilometers . " km</td></tr> "; 
     } 



echo"</table>"; 

你应该避免呼应HTML代码只要有可能。您可以使用PHP Short tags<?=?>将PHP注入您的HTML代码。这条线

echo "<td>" . $close_approach->close_approach_date . "</td>"; 

然后可以改为

<td><?=$close_approach->close_approach_date?></td> 

而且我没有看到任何PHP开始和结束标记(<?php?>)开始和结束你的PHP代码(尽管这可能只是缺乏你的例子

你只是循环你的表数据<td>标签不是你的表行<tr>标签。你必须包括这些在你的循环,以保持在循环创建的每个项目的新表行:

foreach ($near_earth_object->close_approach_data as $close_approach) { 
echo "<tr>"; 

最后,PHP提供了控制结构的替代语法。检查出PHP documentation

PHP为其控制结构提供了一种替代语法;即if,while,for,foreach和switch。在每种情况下,替代语法的基本形式是分别将大括号分别更改为冒号(:)和结束大括号,以分别结束endif,endwhile,endfor ;, endforeach ;,或endswitch。

您可以用它来提高你的现有代码:

foreach ($data->near_earth_objects->$date as $near_earth_object) { 
    echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>"; 
    echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>"; 
    } 

,并把它弄成这个样子

foreach ($data->near_earth_objects->$date as $near_earth_object): ?> 
    <td><?=$near_earth_object->name?> <a href='<?=$near_earth_object->nasa_jpl_url?>'><?=$near_earth_object->nasa_jpl_url?></td> 
    <td><?=$near_earth_object->estimated_diameter->meters->estimated_diameter_min?> metres</td> 
    <? endforeach; ?> 

我建议创建表,你想看到它只是HTML,然后使用PHP动态填充它。有什么可以帮助的是,而不是让PHP回应所有的HTML,只需使用PHP来填充数据(即从显示中分离数据)。正如从here采取了一个例子:

<?php foreach ($things as $thing): ?> 
    <li><?php echo $thing; ?></li> 
<?php endforeach; ?>