【问题标题】:json - get results data from JSON apijson - 从 JSON api 获取结果数据
【发布时间】:2015-11-27 08:32:13
【问题描述】:

我使用 Web API 向许多人发送消息作为我的应用程序目标。该 API 运行良好,并且收到了消息。问题是显示应用程序中发送的消息的结果,无论它们是否发送,接收者等等。从 API 中,它只使用一个变量来显示结果,如下所示:$result = curl_exec($ch);.displaying results like:

Message TestTesting{"response": [{"errors": {"action": "Failed to Send", "error": "No Cost Associated to messages"}}], "success": false}

这样我不能单独格式化结果,或者应用一些 CSS 规则来匹配应用程序。我也看不到阻止消息发送的错误原因(例如低信用余额),因此我不会将其显示给用户。我想获得单个变量。我试图寻找答案,但结果是我使用 JSON 解码。我试过了:

$result = curl_exec($ch);
$json=json_decode($result,true);
print_r($json);

显示如下:

MessageTestingArray ( [response] => Array ( [0] => Array ( [errors] => Array ( [action] => Failed to Send [error] => No Cost Associated to messages ) ) ) [success] => ) 

我尝试使用数组来分别使用“动作”来获取它们:

$result = curl_exec($ch);
$json=json_decode($result,true);
echo $json['action'];

但是结果出现了错误:

Notice: Undefined index: action in C:\xampp\htdocs\glory\process.php on line 75

我怎样才能让它工作?

【问题讨论】:

    标签: php json api


    【解决方案1】:

    $result = curl_exec($ch); $json=json_decode($result,true);

    echo $json['response'][0]['errors']['action'];

    【讨论】:

      【解决方案2】:

      您可以使用@Addil 刚刚发布的内容,但我个人不喜欢在我的代码中硬编码 [0]。 [0] 的存在是有原因的,因此可能会有多个结果。

      $result = curl_exec($ch);
      $json=json_decode($result,true);
      foreach($json['response'] as $response){
      echo $response['errors']['action'];
      }
      

      但请记住在执行 foreach 之前进行检查。查看响应中是否存在带有错误数组的实际数组,否则您将在 foreach 中打印出错误。

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 2012-01-29
        • 2021-05-22
        • 1970-01-01
        相关资源
        最近更新 更多