1
我有這樣的JSON結構:如何在php中反序列化嵌套的json數組?
[
{"product":
{"category_id":1,
"created_at":"2015-06-13 17:49:58",
"description":"CF77 COIN FINDER",
"url_image":"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg",
"name":"CF77 COIN FINDER",
"pid":12,
"price":500.0
},
"product_quantity":3
},
{"product":
{"category_id":1,
"created_at":"2015-06-13 17:49:58",
"description":"JEOSONAR 3D DUAL SYSTEM",
"url_image":"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg",
"name":"JEOSONAR 3D DUAL SYSTEM",
"pid":15,
"price":500.0
},
"product_quantity":1
}
]
而對於反序列化,我已經創建了這兩個類
產品類:
class Product
{
public $pid;
public $name;
public $price;
public $category_id;
public $url_image;
public $description;
public $created_at;
public $updated_at;
public function __construct($pid, $name, $price, $category_id, $url_image, $description, $created_at, $updated_at)
{
$this->pid = $pid;
$this->name = $name;
$this->price = $price;
$this->category_id = $category_id;
$this->url_image = $url_image;
$this->description = $description;
$this->created_at = $created_at;
$this->updated_at = $updated_at;
}
public static function createFromJson($jsonString)
{
$object = json_decode($jsonString);
return new self($object ->pid, $object ->name, $object ->price, $object ->category_id, $object ->url_image, $object ->description, $object ->created_at, $object ->updated_at);
}
}
Command類:
class Command {
public $product;
public $product_quantity;
public function __construct($product, $product_quantity){
$this->product=$product;
$this->product_quantity=$product_quantity;
}
public static function createFromJson($jsonString)
{
$object = json_decode($jsonString);
return new self(Product::createFromJson($object->product), $object ->product_quantity);
}
}
對於簡單的json結構,我可以使用createFromJson
方法,但對於數組,我無法找到反序列化上述json結構的方法。
如何反序列化json數組結構?
$ object = json_decode($ jsonString,true);像這樣使用 – Ramki