简体   繁体   English

使用PHP将组数据库数据编码为JSON

[英]Group Database data encoded as JSON using PHP

Is there anyway to format JSON encoded data that is fetched from mysql Database , with an index ? 无论如何,是否可以使用索引格式化从mysql数据库中获取的JSON编码数据?

Example : 范例

The current JSON i have in text : 我在文本中有当前的JSON:

[{"category_id":"1","category_name":"Luarb1"},{"category_id":"2","category_name":"Luarb2"}]

How i want it to be formatted : 我希望它如何格式化:

{"1":[{"category_id":"1","category_name":"Luarb1"}], "2":[{"category_id":"2","category_name":"Luarb2"}]}
<?php

// init variables
$arr = '[{"category_id":"1","category_name":"Luarb1"},{"category_id":"2","category_name":"Luarb2"}]';
$new = [];

// decode JSON array
$decoded = json_decode($arr);

// create the new array to be encoded
$i = 1;
foreach ($decoded as $cur) {
    $new[$i++] = [$cur];
}

// encode the new array
$encoded = json_encode($new);

// test if everything worked
var_dump($encoded);

// tests.php:15:string '{"1":[{"category_id":"1","category_name":"Luarb1"}],"2":[{"category_id":"2","category_name":"Luarb2"}]}' (length=103)

Here is how I solved your problem, I didn't succeed in starting the array key at 0 but you wanted to be at 1 I think). 这是我解决您问题的方法,我没有成功将数组键从0开始,但我想设为1。

If you want the index from the database entry, you may need to improve your SELECT SQL query and retrieve id, then parse it in JSON and so on... 如果要从数据库条目中获取索引,则可能需要改进SELECT SQL查询并检索ID,然后以JSON解析它,依此类推...

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

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