简体   繁体   English

如何修改我的 PHP 脚本以将 API 作为数组读取?

[英]How can i modify my PHP script to read an API as an array?

I have a PHP script in Wordpress that processes API data if it's an array but I'm having a figuring this out.我在 Wordpress 中有一个 PHP 脚本,如果它是一个数组,它会处理 API 数据,但我有一个解决办法。 Here is my PHP script:这是我的 PHP 脚本:

  $results = wp_remote_retrieve_body( wp_remote_get('https://...') );

  $results = json_decode( $results );   
  
  if( ! is_array( $results ) || empty( $results ) ){
    return false;
  }

Here's what the API looks like.这是 API 的样子。 It' is not an array so how can I modify my above script to support this?:它不是一个数组,所以我如何修改上面的脚本来支持它?:

{
  "msg": "OK",
  "server_time": "2021-03-04 01:42:20",
  "status": 200,
  "result": {
    "total_pages": 2,
    "files": [
      {
        "Country": "USA",
        "city": "NYC",
        "zip: "12345",
      },
      {
        "Country": "RUSSIA",
        "city": "MOSCOW",
        "zip: "12345",
      },
      

The optional second argument to json_decode() indicates whether you want an object or array returned.json_decode()的可选第二个参数指示您是否想要返回 object 或数组。 You're currently getting an object.您当前获得的是 object。 To get an array, pass a truthy value:要获取一个数组,请传递一个真实值:

$results = json_decode($results, true);

json_decode accepts a second parameter which when set to true, returns the JSON object an associative array. json_decode 接受第二个参数,当设置为 true 时,返回 JSON object 一个关联数组。 Therefore, in order to process the data recieved, as you've requested, you'll need to add true, otherwise the JSON object will be returned as object by default.因此,为了处理收到的数据,按照您的要求,您需要添加 true,否则默认情况下 JSON object 将返回为 object。

$results = json_decode( $results, true );  

For more information, see documentation below:有关详细信息,请参阅以下文档:

https://www.php.net/manual/en/function.json-decode.php https://www.php.net/manual/en/function.json-decode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM