2013-09-21 70 views
1

展望輸出JSON的格式如下:建立JSON輸出多維數組

[{"Montgomery":[{"red":"12:34:56","yellow":"11:44:46","orange":"10:54:36","green":"9:24:26","purple":"8:14:16"}],"Suburban":[{"red":"12:34:56","yellow":"11:44:46","orange":"10:54:36","green":"9:24:26","purple":"8:14:16"}],"Shady Grove Adventist":[{"red":"12:34:56","yellow":"11:44:46","orange":"10:54:36","green":"9:24:26","purple":"8:14:16"}],"Holy Cross":[{"red":"12:34:56","yellow":"11:44:46","orange":"10:54:36","green":"9:24:26","purple":"8:14:16"}],"Washington Adventist":[{"red":"12:34:56","yellow":"11:44:46","orange":"10:54:36","green":"9:24:26","purple":"8:14:16"}]}] 

我的代碼:

$xyz[] = array("Montgomery"=> array("Red" => "12:00", "Yellow" => "14:00")); 
$xyz[] = array("Suburban"=> array("Yellow" => "16:00")); 

echo '[' . json_encode($xyz) . ']'; 

我的結果:

[[{"Montgomery":{"Red":"12:00","Yellow":"14:00"}},{"Suburban":{"Yellow":"16:00"}}]] 

回答

2

這會給你的結構:

$container = array(); 
$container['Montgomery'] = array(array('red' => '12:34:56', 'yellow' => '11:44:46')); 
$container['Suburban'] = array(array('red' => '12:34:56', 'yellow' => '11:44:46')); 
echo json_encode(array($container)); 
+0

完美,這正是我所期待的...... @wwwslinger:我想把它全部放在一個數組中,而不是創建一個類,但是出色的選項,謝謝你們兩個。 – BarclayVision

1

你可以使用的對象,這樣的事情(你會希望把它清理乾淨了一下):

class Church { 
    public $red = ""; 
    public $yellow = ""; 
    public $orange = ""; 
    public $green = ""; 
    public $purple = ""; 
} 
class XYZ { 
    public $Montgomery = new Church(); 
    public $Shad_Grove_Adventist = new Church(); 
    public $Holy_Cross = new Church(); 
    public $Washington_Adventist = new Church(); 
} 

$xyz = new XYZ(); 
$xyz->Montgomery->red = "12:00"; 
... 

然後輸出你的JSON:

echo '[' . json_encode($xyz) . ']'; 

這不會是完美的匹配您所需的JSON輸出,但它會提供更好的可讀性和更多的靈活性。

+0

這是一個有效的空間變量嗎? '公共$ Shad_Grove Adventist'? ;) – Jakub

+0

對不起,它需要下劃線。 – wwwslinger

0

您希望輸出有一個數組[]作爲其頂級項目。 JSON中的[]對應於PHP中的數字數組。 JSON數組用於包含有序的項目集合。

您的頂級數組包含一個項目,一個JSON對象{}。 PHP對象(stdClass)或關聯數組將在JSON中轉換爲此。 JSON對象用於創建鍵值對的集合。

要生成所需的輸出,建立你的數據在PHP這樣的:

// Top-level numeric array. 
$container = array(); 

// Only item in top-level array. 
$item = array(); 

// The value of each of these items will be a numeric array. 
$item['Montgomery'] = array(); 

// Create a new associative array, and push that onto the list array. 
$subItem = array("red" => "12:34:56", 
     "yellow" => "11:44:46", 
     "orange" => "10:54:36", 
     "green" => "9:24:26", 
     "purple" => "8:14:16"); 
$item['Montgomery'][] = $subItem; 
$container[] = $item; 

// ...Add more items... 

print json_encode($container); 

或者,如果你想一次建立了一切:

$container = array(
    array(
     "Montgomery" => array(
      array("red" => "12:34:56", 
       "yellow" => "11:44:46", 
       "orange" => "10:54:36", 
       "green" => "9:24:26", 
       "purple" => "8:14:16" 
      ) 
     ) 
     // ...More items... 
    ) 
); 

print json_encode($container); 

注意,也有一些地方是在數組中有一個數組。這是建立一個關聯數組,並將其添加爲數組數組的唯一成員。這對應於在[]內有{}