繁体   English   中英

使用 PHP 和 MySQL 创建多级 JSON

[英]Create multi-level JSON with PHP and MySQL

我不知道如何使用 PHP 和 MySQL 创建多级 JSON 输出。

我有这个查询(针对这个问题进行了简化)

$query = "SELECT 
           1 as id, 
           JSON_OBJECT('key1', 1, 'key2', 'abc') as json1";

我变成了一个数组

while ($row = mysqli_fetch_assoc($result)) {
        $resultArray[] = $row;
}
return $resultArray;

然后使用 json_encode:

echo json_encode($result);

这让我

[
    {
        id: "1",
        json1: "{"key1": 1, "key2": "abc"}"
    }
]

即,变量作为字符串返回。

我想要实现的是将变量 json_test 作为 JSON 的第二级,如下所示:

[
    {
        id: "1",
        json1: 
                  {
                       key1: 1, 
                       key2: "abc"
                  }
    }
]

我已经尝试在这个网站上遵循提示,但没有任何乐趣:

JSON_ARRAY(GROUP_CONCAT(JSON_OBJECT('key1', 1, 'key2', 'abc'))) AS json2

给我

json2: "["{\"key1\": 1, \"key2\": \"abc\"}"]",

CAST(CONCAT('[',GROUP_CONCAT(JSON_OBJECT('key1', 1, 'key2', 'abc')),']') AS JSON) AS json3

给我

json3: "[{"key1": 1, "key2": "abc"}]"

任何提示都非常感谢。

我使用的是 PHP 7.0.25 和 MySQL 5.7.20。

JSON_OBJECT作为字符串返回给 PHP(如prodigitalson评论的那样)

您希望将所有数据作为关联数组。

为了做到这一点,在您发布的例子, json1必须通通过json_decode

while ($row = mysqli_fetch_assoc($result)) {
        $row['json1'] = json_decode( $row['json1'], true ); // <----
        $resultArray[] = $row;
}
return $resultArray;

现在你应该得到想要的结果:

echo json_encode($resultArray);

可以像这样使用 MySQL 构建所需的结构:

mysql> SELECT JSON_OBJECT('id', 1, 'json1', JSON_OBJECT('key1', 1, 'key2', 'abc')) AS obj;
+------------------------------------------------+
| obj                                            |
+------------------------------------------------+
| {"id": 1, "json1": {"key1": 1, "key2": "abc"}} |
+------------------------------------------------+
1 row in set (0.00 sec)

在 PHP 中,我们可以从 JSON 到数组:

php > var_dump(json_decode('{"id":1,"json1":{"key1":1,"key2":"abc"}}', TRUE));
array(2) {
  ["id"]=>
  int(1)
  ["json1"]=>
  array(2) {
    ["key1"]=>
    int(1)
    ["key2"]=>
    string(3) "abc"
  }
}

或数组到 JSON:

php > $tmp = ['id' => 1, 'json1' => ['key1' => 1, 'key2' => 'abc']];
php > var_dump($tmp);
array(2) {
  ["id"]=>
  int(1)
  ["json1"]=>
  array(2) {
    ["key1"]=>
    int(1)
    ["key2"]=>
    string(3) "abc"
  }
}
php > print(json_encode($tmp));
{"id":1,"json1":{"key1":1,"key2":"abc"}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM