嗨,对不起我的英文。用PHP解析mysql数据到json用PHP
我想使用PHP解析从MySQL表中的数据到JSON。 我的表格有2列:'reg','base'代表该地区的地区和基地。 例子:
reg base
KIE KIE1
KIE KIE2
KIE KIE3
ZYT ZYT1
ZYT ZYT2
CHK CHK1
等
我想这个值解析成JSON,看起来像:
{"text":"Bases","leaf":false,"children":{"text":"KIE","leaf":false,"children":[{"text":"KIE1","leaf":true},{"text":"KIE2","leaf":true},{"text":"KIE3","leaf":true}]},{"text":"ZYT","leaf":false,"children":[{"text":"ZYT1","leaf":true},{"text":"ZYT2","leaf":true}]},{"text":"CHK","leaf":false,"children":[{"text":"CHK1","leaf":true}]}}
我的PHP代码:
<?php
header("Content-type: application/json; charset=utf-8");
$conn = mysqli_connect('localhost','test', '123','test');
$bases = array('text'=>'Bases','leaf'=>false);
$regions = "select distinct reg from bases";
$resreg = mysqli_query($conn,$regions);
while($reg=mysqli_fetch_assoc($resreg)){
$bases['children'] = array('text'=>$reg['reg'],'leaf'=>false, 'children'=>array());
$regi = $reg['reg'];
$query = "select base from bases where reg = '$regi' order by 1";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_assoc($result)){
$c = array('text'=>$row['base'],'leaf'=>true);
$bases['children']['children'][]=$c;
}
}
$d = json_encode($bases);
echo $d;
mysqli_close($conn);
?>
这个问题我在JSON中只能从一个reg和don牛逼得到别人的
例子:
{"text":"Bases","leaf":false,"children":{"text":"KIE","leaf":false,"children":[{"text":"KIE1","leaf":true},{"text":"KIE2","leaf":true},{"text":"KIE3","leaf":true}]}
我不知道,这是为了得到我想要的,但我是新来的编程最好的梅托德。
任何人都可以帮助或者告诉我更好的方法来做到这一点? 我需要它为我的ExtJs应用程序树。谢谢。
您每次迭代都会覆盖'$ bases ['children']'。此外,您应该考虑使用JOIN查询来获取此数据,而不是在嵌套循环中运行一堆查询。 – 2014-10-29 14:32:02
@MikeBrant是的,这就是我的想法,但你能解释一下吗?也许查询的例子?我真的不明白为什么我应该使用连接查询在我的情况下:( – fgsfds 2014-10-29 15:32:12