我有一个curl函数来调用一个像这样返回输出的服务
[{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
我想将所有元素回显到表格行
我是怎么做到的?我总是在foreach函数上得到错误。请帮忙
这是我的代码:
<?php
//step1
$cSession = curl_init();
//step2
curl_setopt($cSession,CURLOPT_URL,"http://localhost:8080/packet");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
//
foreach ((array) $result as $item) {
print_r($item['idpacket']);
}
?>
谢谢:)
答案 0 :(得分:1)
我理解了这个结论
编写此代码并检查:
print_r((array)$result);
将JSON放入数组中的位置不会解码您的JSON:
Array
(
[0] => [{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
)
如果你想访问'idpacket'
这样写:
$result_array = json_decode($result,true);
foreach ((array) $result_array as $item) {
print_r($item['idpacket']);
}
答案 1 :(得分:0)
你可以写点像
<?php
$resultArr = json_decode($result,true);
$header="<tr>";
$row="<tr>";
echo "<table>";
foreach($resultArr[0] as $col => $val)
{
$header.="<td>".$col."</td>";
$row.="<td>".$val."</td>";
}
$header.="</tr>";
$row.="</tr>";
echo $header;
echo $row;
echo "</table>";
?>