如何使用定义的格式在php中创建JSON输出

时间:2016-02-22 00:52:53

标签: php json

我应该使用php脚本创建一个JSON输出。 JSON格式是预定义的,所以我无法更改它。这就是它应该是什么样的......

address_pcts = unique_providers %>% 
  group_by(address, city, state) %>%
  filter(n()>5) %>%
  arrange(address) %>%
  summarise(pct_male = sum(gender=="MALE")/n())
library(ggplot2)
qplot(address_pcts$pct_male, binwidth=1/7) + xlim(0,1)

创建头对象和items数组都没有问题。问题是我无法将页面创建为数组,并且无法创建id对象。 pages数组将包含更多“页面”,但我只在下面的代码段中列出一个,因此我需要成为一个数组。

我找到的最接近的解决方案如下......

{
"header": "My header",
"pages": [{
    "id": 1,
    "items": [{
        "header": "My first page",
        "text": "This is my first page"
    }, {
        "header": "My second page",
        "text": "This is my second page"
    }]
  }]
}

这导致..

obj = new stdClass();
$obj->header = "My header";
$obj->pages = array();
$obj->pages["items"][] = array("header" => "My first page", "text" => "This is my first page");
$obj->pages["items"][] = array("header" => "My second page", "text" => "This is my second page");
echo json_encode($obj);

如您所见,此处缺少两部分..

第一件事是页面应该是一个数组,即我错过了[和]括号。 第二个问题是缺少“id”:页面数组中的1个对象,我无法弄清楚如何添加。

非常感谢解决这两个问题的代码示例!

2 个答案:

答案 0 :(得分:2)

如果您将所有{替换为[,将:替换为=>,则很容易,那么您将拥有代表您的目标的php JSON

$json = [
    "header" => "My header",
    "pages" => [
        [
            "id" => 1,
            "items" => [
                [
                    "header" => "My first page",
                    "text" => "This is my first page",
                ], [
                    "header" => "My second page",
                    "text" => "This is my second page",
                ],
            ],
        ],
    ],
];
echo json_encode($json);

从那时起,您可以使用变量提取并替换所需的部分。

答案 1 :(得分:0)

尝试这个,只需创建一个空的php文件,并粘贴我的代码,我已经测试过它以匹配你的:

<?php
    $items = array();
    $pages = array();
    $items[] = array("header" => "My first page", "text" => "This is my first page");
    $items[] = array("header" => "My second page", "text" => "This is my second page");
    $pages[] = array("id" => 1, "items" => $items);
    $obj = array("header" => "My header", "pages" => $pages);
    echo json_encode($obj);
?>