为 json 输出构建多维数组


Build multidimensional array for json output

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

这将为您提供以下结构:

$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));

你可以使用对象,像这样(你需要清理一下):

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

您希望

输出有一个数组[]作为其顶级项。 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);

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