проблемы с парсингом JSON в PHP - PullRequest
0 голосов
/ 01 августа 2020

Я пытаюсь создать базовую c PHP функцию для сайта wordpress, которая считывает ответ JSON от API и берет данные каждого животного для добавления в настраиваемый пост.

У меня возникли проблемы с определением правильного способа разобрать JSON & l oop по животным и их соответствующим данным.

Я знаю, что просто не понимаю JSON структура правильно, и я не разбираю ее должным образом - поэтому надеюсь, что кто-то может направить меня к правильному подходу.

Вот моя функция - проблема на данный момент в l oop is не работает, и я не могу получить данные о животных для заполнения полей.

<?php

//Get advertised animals from ARMS and generate custom post
function get_advertised_animals(){

  $animals = [];
  $results = wp_remote_retrieve_body(wp_remote_get('https://##my-test-API##'));

  $results = json_decode($results);

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

  $animals[] = $results;

  foreach ($animals[0]['Animals'] as $animal){

    $animal_slug = sanitize_title($animal->Name . '-' . $animal->FFAR_ID)

    $inserted_animal = wp_insert_post([
      'post_name' => $animal_slug,
      'post_title' => $animal->Name,
      'post_type' => 'animal',
      'post_status' => 'publish',
      'post_content' => $animal->Biography,
      'post_excerpt' => $animal->Blurb

    ]);

    // Make sure we have the post id
    if ( is_wp_error( $inserted_animal )) {
        continue;
        }

    //Array of all data from the API mapped to the ACF field IDs
    $fillable = [
      'field_5e807346d13f2' => 'Gender',
      'field_5e807363d13f3' => 'Breed',
      'field_5e80736fd13f4' => 'Colour',
      'field_5e807376d13f5' => 'DateOfBirth',
      'field_5e807410d13fb' => 'ExtListURL',
      'field_5e8b1d251e542' => 'AdoptionFee'
      'field_5e807420d13fc' => 'Image1',
      'field_5e8074c2d13fd' => 'image2',
      'field_5e8074cad13fe' => 'Image3',
      'field_5e8074d7d13ff' => 'Image4',
      'field_5e8073b0d13f7' => 'activityLevel',
      'field_5e8073bcd13f8' => 'GoodWithDogs',
      'field_5e8073e7d13f9' => 'GoodWithCats',
      'field_5e8073f7d13fa' => 'GoodwithChildren',
      'field_5e8073a7d13f6' => 'Size'.
      'field_5ea4e481081ed' => 'id'
    ];

    foreach ( $fillable as $key => $name ) {
        update_field ( $key, $animal->$name, $inserted_animal );

      }

  }


}

?>

Вот пример JSON, который отправляется обратно API

{
    "Animals": [
        {
            "Id": 13,
            "Name": "Denver",
            "FFAR_ID": "D200002",
            "Type": "Dog",
            "Breed": "Kelpie x Collie",
            "DateOfBirth": "2020-04-08",
            "Colour": "tan and black",
            "Gender": "Male",
            "AdoptionFee": 750.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/D200002_01_159430",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Yes",
            "GoodWithCats": "Unknown",
            "GoodWithChildren": "Unknown",
            "ActivityLevel": "High"
        },
        {
            "Id": 22,
            "Name": "Diana",
            "FFAR_ID": "C200012",
            "Type": "Cat",
            "Breed": "Domestic Short Hair",
            "DateOfBirth": "2020-02-21",
            "Colour": "Grey/White",
            "Gender": "Female",
            "ExtListURL": "https://www.petrescue.com.au/listings/797984",
            "Biography": "Diana is a beautiful tabby kitten, she’s white with grey spots running down her tail and one grey smudge next to her right ear. If you love sitting down and binge-watching shows, Diana is the purfect companion to join you.\r\n\r\nShe loves finding places to hide when she’s cold, either hiding in the couch or in the TV cabinet. Diana will be fine by herself in her new home as long as she gets a few extra scratches under the chin and behind the ear. She’s more than capable to entertain herself (but wi",
            "AdoptionFee": 200.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Unknown",
            "GoodWithCats": "Yes",
            "GoodWithChildren": "Unknown",
            "ActivityLevel": "Medium",
            "Blurb": "Playful and Gentle"
        },
        {
            "Id": 18,
            "Name": "Katie",
            "FFAR_ID": "C200009",
            "Type": "Cat",
            "Breed": "Domestic Medium Hair",
            "DateOfBirth": "2020-04-06",
            "Colour": "Tabby and white",
            "Gender": "Female",
            "Biography": "This stunning girl will win the hearts of everyone ",
            "AdoptionFee": 250.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "No",
            "GoodWithCats": "Yes",
            "GoodWithChildren": "Yes",
            "ActivityLevel": "Medium",
            "Blurb": "Beautiful Katie"
        },
        {
            "Id": 15,
            "Name": "Lily (and Sooty)",
            "FFAR_ID": "C200006",
            "Type": "Cat",
            "Breed": "Birman",
            "DateOfBirth": "2007-05-01",
            "Colour": "White with black point",
            "Gender": "Female",
            "ExtListURL": "https://www.petrescue.com.au/listings/797968",
            "Biography": "Sooty and Lily are a great pair for a calm, quiet, and loving home. Sooty is a super easy going deaf boy who loves cuddles all day long. True to his bread he is vocal and with his deafness he can be loud.\r\n\r\nLily prefers to keep more to herself, but when she decides she likes you she’ll come and sit on your lap rolling over and asking for cuddles. She particularly loves scratches on the head and bum! They spend most of the day sitting staring outside the window at the world moving past, but she’",
            "AdoptionFee": 75.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Unknown",
            "GoodWithCats": "Unknown",
            "GoodWithChildren": "No",
            "ActivityLevel": "Low",
            "Blurb": "A majestic pair"
        },
        {
            "Id": 9,
            "Name": "Mickey",
            "FFAR_ID": "C200002",
            "Type": "Cat",
            "Breed": "Domestic Medium Hair",
            "DateOfBirth": "2020-04-06",
            "Colour": "Black and white",
            "Gender": "Male",
            "Biography": "Mickey is a super loving, cuddly, playful kitten ",
            "AdoptionFee": 250.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Yes",
            "GoodWithCats": "Yes",
            "GoodWithChildren": "Yes",
            "ActivityLevel": "Medium",
            "Blurb": "Affectionate "
        },
        {
            "Id": 14,
            "Name": "Rory",
            "FFAR_ID": "D200003",
            "Type": "Dog",
            "Breed": "Kelpie x Collie",
            "DateOfBirth": "2020-04-08",
            "Colour": "black with a white sock",
            "Gender": "Female",
            "AdoptionFee": 750.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Medium",
            "GoodWithDogs": "Yes",
            "GoodWithCats": "Unknown",
            "GoodWithChildren": "Unknown",
            "ActivityLevel": "High"
        },
        {
            "Id": 12,
            "Name": "Sooty (and Lily)",
            "FFAR_ID": "C200005",
            "Type": "Cat",
            "Breed": "Birman",
            "DateOfBirth": "2007-05-01",
            "Colour": "White with black point",
            "Gender": "Male",
            "ExtListURL": "https://www.petrescue.com.au/listings/797968",
            "Biography": "Sooty and Lily are a great pair for a calm, quiet, and loving home. Sooty is a super easy going deaf boy who loves cuddles all day long. True to his bread he is vocal and with his deafness he can be loud.\r\n\r\nLily prefers to keep more to herself, but when she decides she likes you she’ll come and sit on your lap rolling over and asking for cuddles. She particularly loves scratches on the head and bum! They spend most of the day sitting staring outside the window at the world moving past, but she’",
            "AdoptionFee": 75.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Unknown",
            "GoodWithCats": "Unknown",
            "GoodWithChildren": "No",
            "ActivityLevel": "Low",
            "Blurb": "A majestic pair"
        },
        {
            "Id": 6,
            "Name": "Terry",
            "FFAR_ID": "C200001",
            "Type": "Cat",
            "Breed": "DSH",
            "DateOfBirth": "2020-03-02",
            "Colour": "Grey Tabby",
            "Gender": "Male",
            "ExtListURL": "https://thatsite.com",
            "Biography": "Terry says meow",
            "AdoptionFee": 100.00000000,
            "Image1": "https://devarms.blob.core.windows.net/images/",
            "Image2": "https://devarms.blob.core.windows.net/images/",
            "Image3": "https://devarms.blob.core.windows.net/images/",
            "Image4": "https://devarms.blob.core.windows.net/images/",
            "Size": "Small",
            "GoodWithDogs": "Unknown",
            "GoodWithCats": "Unknown",
            "GoodWithChildren": "Unknown",
            "ActivityLevel": "Low",
            "Blurb": "meow"
        }
    ],
    "Result": {
        "Success": true
    }
}

Заранее благодарим за любую помощь.

Ответы [ 2 ]

0 голосов
/ 01 августа 2020

Попробуйте это. Измените область ниже:

     $results = wp_remote_retrieve_body(wp_remote_get('https://##my-test-API##'));
    
      $animals = json_decode($results);
    
      if ( ! is_array($results) || empty ($results) ){
        return false;
      }
    
    //  $animals[] = $results;
    
      foreach ($animals['Animals'] as $animal){
   // Your code here
      }
0 голосов
/ 01 августа 2020

Вы получаете доступ к объекту Animals из json, поэтому вам следует изменить его на:

foreach ($animals[0]->Animals as $animal) {

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...