第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

PHP 對象到 JSON:如何創(chuàng)建具有多個遞歸子級的類?

PHP 對象到 JSON:如何創(chuàng)建具有多個遞歸子級的類?

PHP
繁花不似錦 2023-06-24 17:57:13
我需要創(chuàng)建一個 PHP 類,該類將具有該類的多個父子關(guān)系,以便轉(zhuǎn)換后的 JSON 字符串看起來與此類似。如果“children”為空數(shù)組,如何使其不出現(xiàn)在 JSON 中?{   name: "Element Parent",    code: "000"    children: [        {            name: "Element Child 1"            code: "001"            children: [                {                    name: "Element Child 1A"                    code: "001A"                },                {                    name: "Element Child 1B"                    code: "001B"                    children: [                        {                            name: "Element Child 1BA"                            code: "001BA"                        }                    ]                }            ]        }        ,        {            name: "Element Child 2"            code: "002"        }    ]}我正在嘗試創(chuàng)建一個可以轉(zhuǎn)換為上面的 JSON 字符串的 PHP 類。<?phpclass Element implements \JsonSerializable{    private $name;    private $code;        public function __construct($name, $code, )    {        $this->name = $name;        $this->code = $code;    }        public function jsonSerialize()    {        return get_object_vars($this);    }        public function toJSON(){        return json_encode($this);    }        public $children[] = array(); // to contain Element children class }$element = new Element("Element Parent", 000);$elementChild1 = new Element("Element Child 1", "001");$elementChild1A = new Element("Element Child 1A", "001A");$elementChild1B = new Element("Element Child 1B", "001B");$elementChild1BA = new Element("Element Child 1BA", "001BA");$elementChild1B->children[] = $elementChild1BA;$elementChild1->children[] = $elementChild1A;$elementChild1->children[] = $elementChild1B;$element->children[] = elementChild1;$elementChild2 = new Element("Element Child 2", "002");$element->children[] = elementChild2;echo $element->toJSON();?>非常感謝。
查看完整描述

1 回答

?
慕容森

TA貢獻(xiàn)1853條經(jīng)驗 獲得超18個贊

在jsonSerialize您實現(xiàn)的函數(shù)中,您可以更改序列化行為。在那里,您可以檢查是否有兒童,并在需要時將其留在外面。在這種情況下,你最終會得到這樣的結(jié)果:


public function jsonSerialize() {

  $data = [

    "name" => $this->name,

    "code" => $this->code

  ];


  if(!empty($this->children)) {

    $data["children"] = $this->children;

  }


  return $data;

}


查看完整回答
反對 回復(fù) 2023-06-24
  • 1 回答
  • 0 關(guān)注
  • 128 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號