【发布时间】:2019-01-13 20:53:41
【问题描述】:
我正在为来自curl_exec json GET 请求的每个结果创建 div。我已经在 PHP 中使用 cURL 尝试了下面的代码。当我运行这段代码时,foreach 没有任何内容。
//API Url
$url = 'https://api.clover.com:443/v3/merchants/'.$merchantid.'/categories/';
//Initiate cURL.
$ch = curl_init($url);
$headers = array(
'Content-type: application/json',
'Authorization: Bearer '.$authtoken.' ',
);
//Tell cURL that we want to send a GET request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$resp = curl_exec($ch);
$respArray = json_decode($resp, true);
foreach($respArray as $key => $value) {
echo $key . " : " . $value;
}
curl_close($ch);
这将返回以下内容:
{
"elements": [
{
"id": "QWS8MSMAT49E6",
"name": "Other",
"sortOrder": 2
},
{
"id": "35K000MJVVFHE",
"name": "Pizza",
"sortOrder": 1
}
],
"href": "http://api.clover.com/v3/merchants/{[MID]}/categories?limit=100"
}
我正在尝试将上面的信息放入一个div中,例如:
【问题讨论】:
-
您是否收到任何错误或通知?看起来你在 foreach 循环中处理数组
$respArray。但是你应该申请$respArray["elements"]。 -
@LucaJung 我刚刚检查了 PHP 日志,发现
PHP Warning: Invalid argument supplied for foreach()。当你说我应该申请$respArray["elements"]你是什么意思?我的代码将在哪里进行更改?我可能错过了它的重点。感谢您的回复。 -
你能发布
var_dump($respArray);的输出吗?我的意思是将这一行foreach($respArray as $key => $value)更改为foreach($respArray["elements"] as $key => $value)。 -
@LucaJung 从
var_dump($respArray);获取int(1) -
如果你得到
int(1)返回,你从哪里得到返回信息?
标签: php arrays json curl foreach