无论如何,是否有格式来格式化从中获取的JSON编码数据
mysql数据库,有索引吗?
范例:
我在文本中有当前的JSON:
[{"category_id":"1","category_name":"Luarb1"},{"category_id":"2","category_name":"Luarb2"}]
我希望它如何格式化:
{"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)
这是我解决您问题的方法,我没有成功将数组键从0开始,但是我想设为1。
如果要从数据库条目中获取索引,则可能需要改进SELECT SQL查询并检索ID,然后以JSON解析它,依此类推...
关于php - 使用PHP将组数据库数据编码为JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40999066/