Object Representation - PHP
I'm trying to understand how to best represent data which eventually I'll pull out and build JSON / XML from.. however I keep running in circles of how to define the object..
Essentially I want to represent a parent / child relationship along with what attributes are on the item. Such that I could build a JSON or XML element.
Has anyone worked with something like this before or have any ideas on how to work through it?
My XML built would look something like:
<props>开发者_Python百科
<items>
<item id='foo'/>
<item id='foo2' />
</items>
<bar>
<test>
<tree>This Data</tree>
<tree>That Data</tree>
</test>
</bar>
</props>
I thought of some how trying to represent each data item in an object as:
class ItemResource {
private $key;
private $value;
private $attribute_list = array();
public function __construct($key, $value, array $attributeList=null){
$this->key = $key;
$this->value = $value;
if($attributeList!=null){
//do stuff
$this->attribute_list = $attributeList;
}
}
}
Sounds like an excellent job for PHP's Array. You can build infinitely large key-value hierarchies using associative arrays.
$itemresource = array(
"key" => $key,
"value" => $value,
"attribute_list" => array(
"foo" => "bar",
"some" => "value"
)
);
Associative arrays are also probably the input for XML generators (Although that's guesswork from my side)
You can also easily print your arrays out in JSON using json_encode
精彩评论