嗨,對不起我的英文。用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