mysql json多级,使用PHP和MySQL创建多级JSON

I can't figure out how to create a multi-level JSON output using PHP and MySQL.

I have this query (simplified for this question)

$query = "SELECT

1 as id,

JSON_OBJECT('key1', 1, 'key2', 'abc') as json1";

which I turn into an array

while ($row = mysqli_fetch_assoc($result)) {

$resultArray[] = $row;

}

return $resultArray;

and then use json_encode:

echo json_encode($result);

This gets me

[

{

id: "1",

json1: "{"key1": 1, "key2": "abc"}"

}

]

i.e., the variable is returned as a string.

What I would like to achieve is to have the variable json_test as a second level of JSON, like so:

[

{

id: "1",

json1:

{

key1: 1,

key2: "abc"

}

}

]

I have tried following hints around this site, but no joy:

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

gives me

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

and

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

gives me

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

Any hints are greatly appreciated.

I'm on PHP 7.0.25 and MySQL 5.7.20.

解决方案

The JSON_OBJECT is returned to PHP as a string (as prodigitalson commented)

You want to have all your data as an associative array.

In order to do that, in the example you posted, json1 must be passed thru json_decode.

while ($row = mysqli_fetch_assoc($result)) {

$row['json1'] = json_decode( $row['json1'], true ); //

$resultArray[] = $row;

}

return $resultArray;

Now you should get the desired result:

echo json_encode($resultArray);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值