【问题标题】:Illegal string offset foreachforeach 非法字符串偏移
【发布时间】:2020-11-29 06:42:18
【问题描述】:

我有这段代码,当我在页面底部使用 foreach 时出现错误。

<table>
<tr>
<?php
   $data =('https://www.example.com/api/report_advertiser?key=abcd&campaigns=6757955,6781745,6739793,6349821&quick=last_month');
   $data_json = json_encode($data);
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $data);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $response  = curl_exec($ch);
   curl_close($ch);
   foreach ($response as $value)
   echo $value['campaigns']
?>
</tr>
</table>

【问题讨论】:

标签: php api loops post foreach


【解决方案1】:
$response = curl_exec($ch);

看这段代码应该知道curl_exec()返回一个字符串,当执行成功,否则false

但在下一步中,您将遍历一个字符串

foreach ($response as $value) {
    echo $value['campaigns'];
}

您只能迭代 iterable 类型,如数组。

看起来您期望一个 JSON 字符串,您可以将其转换为数组。为此使用 json_decode() 并将 true 作为第二个参数传递以接收关联数组而不是对象。

假设您将收到一个具有内部循环键 campaigns 的多维数组,下面的代码将完成这项工作。

$response = json_decode($response, true);

foreach ($response as $value) {
    echo $value['campaigns'];
}

更新 1

使用你之前提供的 URL(我匿名了,因为你提交了凭据)你会收到一个错误。

if (!empty($response['errors'])) {
    throw new Exception(print_r($response['errors'], true));
}

给出了following,所以它不能像你期望的那样工作,因为数据根本不可用。

[状态] => 405
[代码] => 13
[title] => 此操作不允许使用方法

【讨论】:

  • 我说,假设数据就像你试图解析的那样。举一个你的 JSON 的例子,我会更新
猜你喜欢
  • 2020-06-11
  • 1970-01-01
  • 2013-09-29
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2017-09-13
  • 1970-01-01
相关资源
最近更新 更多