1

希望以以下格式输出 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"}}]] 
4

3 回答 3

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));
于 2013-09-21T23:29:51.573 回答
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 输出完美匹配,但它会提供更好的可读性和更大的灵活性。

于 2013-09-21T23:41:47.627 回答
0

你想要的输出有一个数组[]作为它的顶级项目。[]JSON 中对应于 PHP 中的数值数组。JSON 数组用于包含有序的项目集合。

您的顶级数组包含一项,即 JSON 对象{}。PHP 对象 (stdClass) 或关联数组将在 JSON 中转换为 this。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);

请注意,有些地方在数组内有一个数组。这是建立一个关联数组并将其添加为数值数组的唯一成员。这对应于有一个{}inside []

于 2013-09-22T00:23:13.223 回答