PHP数组到HTML表问题
我的代码在某种程度上可以工作,因为它将我的数组回显到表中——但问题是,它回显所有字段 我只想显示名称、培训师和状态字段。我就是不知道该怎么做 排列 PHP代码如下所示PHP数组到HTML表问题,php,arrays,Php,Arrays,我的代码在某种程度上可以工作,因为它将我的数组回显到表中——但问题是,它回显所有字段 我只想显示名称、培训师和状态字段。我就是不知道该怎么做 排列 PHP代码如下所示 <?php if (count($obj) > 0): ?> <table> <thead> <tr> <th><?php echo implode('</th><th>', array_keys(current
<?php if (count($obj) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($obj))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($obj as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
$jsondata=file\u get\u contents($api\u url);
$obj=json_decode($jsondata,true);
if(is_数组($obj)){
回声“;
呼应“NameTrainerStatus”;
foreach($obj作为$row){
数组映射('htmlentities',$row);
回声“;
回显“$row[“name”]”;
回显“$row[“trainer”]”;
回显“$行[“状态”]”;
回声“;
}
回声“;
}
调用array\u map()
以使用htmlentities
修改每行中的每个值是没有意义的,因为您只显示其中的三个值——只修改要显示的内容
代码:()
$json\u data=file\u get\u contents($api\u url);
$objects=json\u decode($json\u数据);
if(is_数组($objects)&&sizeof($objects)){
回声';
echo“NameTrainerStatus”;
回声';
foreach($对象作为$行){
回声';
echo“”,htmlentities($row->name),“”;
echo'',htmlentities($row->trainer),'';
回显“”,HTML属性($row->status),“”;
回声';
}
回声';
}否则{
回显“接收到无效或空的json数据”;
}
输出:
<table>
<thead>
<tr>
<th>Name</th>
<th>Trainer</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castarnie</td>
<td>Robert Walford</td>
<td>WINNER</td>
</tr>
<tr>
<td>Try It Sometime</td>
<td>Sheila Lewis</td>
<td>LOSER</td>
</tr>
</tbody>
</table>
名称
教练
地位
卡斯塔尼
罗伯特·沃尔福德
赢家
找个时间试试吧
希拉·刘易斯
失败者
您的PHP
函数,用于生成该数组。它来自json api$jsondata=file\u get\u contents($api\u url)$obj=json_decode($jsondata,true);谢谢你抽出时间!非常感谢。但是它得到了一个500错误?在第二行中缺少一个分号,例如,在使用htmlspecialchars
修复XSS后修复
$jsondata = file_get_contents($api_url);
$obj = json_decode($jsondata, true);
if (is_array($obj)){
echo "<table>";
echo "<th><td>Name</td><td>Trainer</td><td>Status</td></tr>";
foreach ($obj as $row){
array_map('htmlentities', $row);
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["trainer"]."</td>";
echo "<td>".$row["status"]."</td>";
echo "</tr>";
}
echo "</table>";
}
$json_data=file_get_contents($api_url);
$objects=json_decode($json_data);
if(is_array($objects) && sizeof($objects)){
echo '<table><thead><tr>';
echo '<th>Name</th><th>Trainer</th><th>Status</th>';
echo '</tr></thead><tbody>';
foreach($objects as $row){
echo '<tr>';
echo '<td>',htmlentities($row->name),'</td>';
echo '<td>',htmlentities($row->trainer),'</td>';
echo '<td>',htmlentities($row->status),'</td>';
echo '</tr>';
}
echo '</tbody></table>';
}else{
echo 'Invalid or empty json data received';
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Trainer</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castarnie</td>
<td>Robert Walford</td>
<td>WINNER</td>
</tr>
<tr>
<td>Try It Sometime</td>
<td>Sheila Lewis</td>
<td>LOSER</td>
</tr>
</tbody>
</table>