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

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

如何在 json 中正確格式化 WP_REST_Response 并獲取數組而不是對象?

如何在 json 中正確格式化 WP_REST_Response 并獲取數組而不是對象?

蠱毒傳說 2021-06-06 13:15:53
我正在用 wordpress 構建一個非常小的應用程序,需要通過 ajax 獲取 json 數據。我正面臨一個奇怪的(至少對我而言)問題。我的原始數據日志是這樣的(請注意items和children>它們是數組):object(stdClass)#6740 (2) {  ["type"]=>  string(5) "areas"  ["items"]=>  array(1) {    [92]=>    object(stdClass)#6742 (10) {      ["term_id"]=>      int(92)      ["name"]=>      string(6) "Italia"      ["slug"]=>      string(6) "italia"      ["term_taxonomy_id"]=>      int(92)      ["taxonomy"]=>      string(12) "dealer_areas"      ["description"]=>      string(0) ""      ["parent"]=>      int(82)      ["count"]=>      int(1)      ["term_order"]=>      float(0.1)      ["children"]=>      array(1) {        [126]=>        object(stdClass)#6741 (10) {          ["term_id"]=>          int(126)          ["name"]=>          string(8) "Sardegna"          ["slug"]=>          string(8) "sardegna"          ["term_taxonomy_id"]=>          int(126)          ["taxonomy"]=>          string(12) "dealer_areas"          ["description"]=>          string(0) ""          ["parent"]=>          int(92)          ["count"]=>          int(1)          ["term_order"]=>          float(0.10003)          ["children"]=>          array(0) {          }        }      }    }  }}如果我將它直接傳遞給 WP_REST_Response,然后作為 json 響應 ( return new WP_REST_Response($response_obj))傳遞給 js ,我會得到這樣的日志:正如你所看到的,它不完全是 json ......有 getter/setter 方法..好的,然后我傳遞值 json 編碼 ( return new WP_REST_Response(json_encode($response_obj))) 并通過 javascript 解析JSON.parse()。我明白了:或者這個(另一個例子超過 1 個 obj)如您所見,我得到了 json,但即使原始項目數據是一個數組,現在我也得到了一個對象。如何保留原始數組類型?
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

我自己的回答是:

  1. 這不是 WP_REST_Response 問題。

  2. 這不是 json_decode 問題

  3. 問題是數據格式和javascript讀取數組的方式

簡而言之:不可能將 php 非連續索引數組轉換為 javascript 數組,因為 javascript 需要連續的整數鍵。在所有其他情況下,javascript 讀取為關聯數組或對象(本質上是相同的)。因此,php非連續索引數組的json轉換總會輸出對象。


查看完整回答
反對 回復 2021-06-11
  • 1 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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