我需要使用PHP創建JSON對象,因爲我需要爲像XML這樣的每個節點賦予屬性我不能只創建一個PHP數組(我認爲)的負載,所以我創建PHP對象,並以這種方式。在PHP中創建JSON對象
問題是我可以完全正確地格式化JSON。
這就是我想:
$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;
,輸出:
{
"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"}
}
}
我需要 「2」 的第一個節點具有屬性 「稱號」 的: 「畫廊」,「項「:」123「,但也包含」過去「和」現在「的子節點,多年來也一樣。
在XML中,可能是這個樣子:
<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/>
我不明白,爲什麼你不能只用數組這一點。 – vcanales 2014-10-27 16:23:18
可能重複[簡單的jQuery,PHP和JSONP示例?](http://stackoverflow.com/questions/6809053/simple-jquery-php-and-jsonp-example) – MontrealDevOne 2014-10-27 16:39:30
其實你是對的我可以devJunk。 – Kline 2014-10-27 16:47:05