为json输出构建多维数组

时间:2013-09-21 23:20:34

标签: php 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"}}]] 

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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输出完美匹配,但它会提供更好的可读性和更大的灵活性。

答案 2 :(得分: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);

请注意,有些地方在数组中有一个数组。这是为了构建一个关联数组并将其添加为数值数组的唯一成员。这相当于{}[]