在 PHP 中,我有一个包含属性集合的产品对象。json_encode 产生这个:
{"id":"123","name":"abc","attributes":{"attributes":[{"key":"sku","value":"xyz"}]}}
列出两次的“属性”是多余的。构造对象集合以使 json 干净的最佳方法是什么?
class Product {
public $id;
public $name;
public $attributes;
public function __construct()
{
$this->attributes = new Attributes();
}
public function get($id)
{
$this->id = "123";
$this->name = "abc";
$attribute = new Attribute("sku", "xyz");
$this->attributes->add($attribute);
}
}
class Attributes
{
public $attributes;
public function __construct()
{
$this->attributes = array();
}
public function add($attribute)
{
array_push($this->attributes, $attribute);
}
}
class Attribute
{
public $key;
public $value;
public function __construct($key, $value)
{
$this->set($key, $value);
}
}