【发布时间】:2021-08-03 08:13:38
【问题描述】:
我需要在 PHP 中解析 JSON 数组响应并在 HTML 表中回显这些值。我对 PHP-JSON 很陌生,我无法找到这样做的方法。
$curl_response = curl_exec($curl);
echo $curl_response . PHP_EOL;
JSON 数组响应:
{
"employees": [
{
"emp_id":101,
"name":"Christ Joseph",
"email":"emp101@example.com",
"attendance": [
{
"last_day_present":"13-05-2021",
"days_present":0,
"grade":A
}
]
},
{
"emp_id":102,
"name":"Paolo Jobh",
"email":"emp102@example.com",
"attendance": [
{
"last_day_present":"13-05-2021",
"days_present":100,
"grade":B
}
]
},
{
"emp_id":103,
"name":"Subo Paul",
"email":"emp103@example.com",
"attendance": [
{
"last_day_present":"13-05-2021",
"days_present":15,
"grade":B
}
]
},
]
}
PHP 脚本:
$json = json_decode($curl_response, true);
echo "<table border='1' width='50%' align='center'>";
foreach($json['employees'] as $data)
{
if($json['employees'][0]['attendance']['days_present'] == 0) {
//exclude the employees whose days_present is 0
} else {
echo "<tr>";
echo "<td>$json['employees']['emp_id']</td>";
echo "<td>$json['employees']['email']</td>";
echo "<td>$json['employees']['days_present']</td>";
echo "<td>$json['employees'][0]['attendace']['grade']</td>";
echo "</tr>";
}
}
获取输出:
(empty table)
预期输出:
<table border="1" width="50%" align="center">
<!-- Display the JSON array response here -->
<tr>
<td>102</td>
<td>emp102@example.com</td>
<td>100</td>
<td>B</td>
</tr>
<tr>
<td>103</td>
<td>emp103@example.com</td>
<td>15</td>
<td>B</td>
</tr>
有人,请帮我弄清楚脚本有什么问题。有没有更好的方法可以更快地执行脚本并减少流量负载?
【问题讨论】:
标签: php arrays json curl php-curl