我有两张桌子,
1 - 类别
2 - 子类别
Category (table 1)
---------------
Cid | Name
1 | Vegetable
2 | Fruit
SubCategory (table 2)
----------------
Cid | Sid | S_name
1 | 1 | Carrot
1 | 2 | Beans
2 | 3 | Mango
我想在Json中得到这样的结果: -
-> Category found
-> Vegetable
-> carrot
-> beans
-> Fruit
-> mango
我正在使用下面的代码!任何人都可以帮我纠正我的代码和得到像我上面提到的输出!我多次尝试过。但没有得到解决方案!请帮我获取目录表单的输出。感谢
`$srtResult = "SELECT * FROM `category` `c` LEFT JOIN `subcategory` `s` ON
(`c`.`cid` = `s`.`cid`)";
//Execute Qu**strong text**ery
$result=mysql_query($srtResult);
//Iterate Throught The Results
while ($row = mysql_fetch_assoc($result, MYSQL_ASSOC))
{ $count = $row['cid'];
while($row['cid'] = $count)
{ $subcatitem[] = Array( "cid" => $row['cid'], "sid" =>$row['sid'],
"sname" => $row['sc_name'] );
}
$json['category'][] = Array("category" => Array( "cid" => $row['cid'],
"name" => $row['name'], "subcategory" => Array( $subcatitem)));
}
header('Content-type: application/json');
echo json_encode($json);`
答案 0 :(得分:0)
这不够吗?
$srtResult = "SELECT * FROM `category` `c` LEFT JOIN `subcategory` `s` ON
(`c`.`cid` = `s`.`cid`)";
$result = mysql_query($srtResult);
while ($row = mysql_fetch_assoc($result, MYSQL_ASSOC)) {
$json['category'][$row['name']] = $row['sc_name'];
}
header('Content-type: application/json');
echo json_encode($json);
修改强>
在注释中进行了更多解释后,所需的PHP数组结构(给出预期的JSON字符串)应如下所示:
Array
(
[success] => 1
[message] => Category found in Database
[Category] => Array
(
[0] => Array
(
[id] => 1
[name] => vegetable
[Subcategory] => Array
(
[0] => Array
(
[cid] => 1
[sid] => 1
[sc_name] => carrot
)
[1] => Array
(
[cid] => 1
[sid] => 2
[sc_name] => beans
)
)
)
[1] => Array
(
[id] => 2
[name] => Fruit
[Subcategory] => Array
(
[0] => Array
(
[cid] => 1
[sid] => 1
[sc_name] => Mango
)
)
)
)
)