2014-07-15 78 views
0

我有一個php對象,我想將其轉換爲以下json格式。將php對象轉換爲json

所有data值是通過在格式php對象對象:

Array ([0] => stdClass Object ([id] => 2 
           [s1] => 1485 
           [name] => 1485 
           [credit] => '' 
           [caption] => '' 
           ) 
    ) 

child下試圖組credit, caption等。此外,我無法獲得date格式的json格式之後的[

{ 
    "mydata": 
    { 
     "name":Name, 
     "type":"default", 
     "date": [ 
     { 
       "s1":"1485", 
       "name":"1485", 
       "child": 
       { 
        "credit":"", 
        "caption":"" 
       } 
      }] 
    } 
} 

目前,我的代碼如下所示:

foreach ($hits as $hit) { 
    $data->mydata->date->s1 = $hit->s1; 
    $data->mydata->date->name = $hit->name; 
    $data->mydata->date->credit = $hit->credit; 
    $data->mydata->date->caption = $hit->caption; 
} 
$a = json_encode($data); 

回答

0

設置$date->mydata->date到一個數組,你會得到[]

爲什麼不使更多的嵌套結構?

0

你看JSON格式顯示的日期是一個數組(括號內是在JavaScript數組符號),所以:

<?php 

$var = array(
    'mydata' => array(
     'name' => 'Name', 
     'type' => 'default', 
     'date' => array(
      array(
       's1' => 1485, 
       'name' => '1485', 
       'child' => array(
        'credit' => '', 
        'caption' => '', 
       ), 
      ), 
     ), 
    ), 
); 

print json_encode($var); 

打印出:

{ 
    "mydata": { 
     "name": "Name", 
     "type": "default", 
     "date": [ 
      { 
       "s1": 1485, 
       "name": "1485", 
       "child": { 
        "credit": "", 
        "caption": "" 
       } 
      } 
     ] 
    } 
} 

無需嘗試在PHP中添加stdClass實例或類似的東西。只需構建一個漂亮的清潔數組,JSON編碼將在必要時轉換爲對象屬性和數組。