I need to create a JSON object using PHP, as I need to give attributes to each node like XML uses I can't just create a load of PHP arrays (I think), so I am creating PHP objects and doing that way.
The problem is I can quite get the JSON formatted properly.
This is what I am trying:
$object = new stdClass();
$object->{'0'}['title'] = 'Home';
$object->{'0'}['entry'] = '123';
$object->{'1'}['title'] = 'About';
$object->{'1'}['entry'] = '123';
$object->{'2'}['title'] = 'Gallery';
$object->{'2'}['entry'] = '123';
$object->{'2'} = new stdClass();
$object->{'2'}->{'0'}['title'] = 'Past';
$object->{'2'}->{'0'}['entry'] = '1234';
$object->{'2'}->{'1'}['title'] = 'Present';
$object->{'2'}->{'1'}['entry'] = '1235';
$object->{'2'}->{'0'} = new stdClass();
$object->{'2'}->{'0'}->{'0'}['title'] = '1989';
$object->{'2'}->{'0'}->{'0'}['entry'] = '12345';
$object->{'2'}->{'0'}->{'1'}['title'] = '1990';
$object->{'2'}->{'0'}->{'1'}['entry'] = '12346';
$ob=json_encode($object);
echo $ob;
Which outputs:
{
"0":{"title":"Home","entry":"123"},
"1":{"title":"About","entry":"123"},
"2":{
"0":{
"0":{"title":"1989","entry":"12345"},
"1":{"title":"1990","entry":"12346"}},
"1":{"title":"Present","entry":"1235"}
}
}
I need "2" of the first node to have attributes "title":"Gallery","entry":"123" but also contain the sub nodes for Past and Present, with the same again for the years.
In XML it may look something like this:
<0 title="Home" entry="123">
<0/>
<1 title="About" entry="123">
<1/>
<2 title="Gallery" entry="123">
<0 title="Past" entry="1234">
<0 title="1989" entry="12345"><0/>
<1 title="1990" entry="12346"><1/>
<0/>
<1 title="Present" entry="1235">
<1/>
<2/>