组数据库数据编码为JSON使用PHP
问题描述:
是否有任何格式的JSON编码数据是从 mysql数据库,索引?组数据库数据编码为JSON使用PHP
例:
目前的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等等...
这不是一个有效的JSON – Federkun
@Federkun打招呼,该json被回显使用:\t $ row = $ stmt-> fetchAll(PDO :: FETCH_ASSOC); return \t json_encode($ row); –
要清楚,第一个是有效的,第二个不是。第二阶段发生了什么 - 你是否希望他们编号,或者是否希望category_id作为每个条目的前缀? – WillardSolutions