skip to Main Content

I have a PHP script in WordPress that processes API data if it’s an array but I’m having a figuring this out. Here is my PHP script:

  $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. 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",
      },
      

2

Answers


  1. The optional second argument to json_decode() indicates whether you want an object or array returned. You’re currently getting an object. To get an array, pass a truthy value:

    $results = json_decode($results, true);
    
    Login or Signup to reply.
  2. json_decode accepts a second parameter which when set to true, returns the JSON object an associative array. 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.

    $results = json_decode( $results, true );  
    

    For more information, see documentation below:

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search