亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP 中解析 JSON 的問題

PHP 中解析 JSON 的問題

PHP
慕容森 2023-09-08 21:42:30
我正在嘗試為 WordPress 網站創建一個基本的 PHP 函數,該函數讀取來自 API 的 JSON 響應,并將每種動物的數據添加到自定義帖子中。我在弄清楚解析 JSON 和循環動物及其各自數據的正確方法時遇到了一些麻煩。我知道這只是我沒有正確理解 JSON 結構,并且我沒有以正確的方式解析它 - 所以希望有人可以指導我正確的方法。這是我的函數 - 目前的問題是循環不起作用,我無法獲取動物數據來填充字段。<?php//Get advertised animals from ARMS and generate custom postfunction 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 );      }  }}?>
查看完整描述

2 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

嘗試這個。更改以下區域:


     $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

      }


查看完整回答
反對 回復 2023-09-08
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

Animals您正在從 json訪問該對象,因此您應該將其更改為:

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


查看完整回答
反對 回復 2023-09-08
  • 2 回答
  • 0 關注
  • 117 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號