我试图将这些结果放到PHP中的数组中,以便我可以将它们编码为json对象。
我希望json对象看起来像这样:
{"ShopApp":[{"cid":"31","category_name":"Category 1","category_image":"99520_category1.png","subcat":[{"sub_cat_id":"243","sub_cat_name":"Sub Category1"},{"sub_cat_id":"244","sub_cat_name":"Sub Category2"},{"sub_cat_id":"245","sub_cat_name":"Sub Category3"},{"sub_cat_id":"245","sub_cat_name":"Sub Category4"}]},{"cid":"31","category_name":"Category 2","category_image":"99520_category1.png","subcat":[{"sub_cat_id":"1243","sub_cat_name":"Sub Category5"},{"sub_cat_id":"1244","sub_cat_name":"Sub Category6"},{"sub_cat_id":"1245","sub_cat_name":"Sub Category7"}]}]}
这是我的代码。这将返回一个json对象数组
$SQL = "SELECT cid,category_name,category_image FROM tbl_category";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[$row['id']]['cid'] = $row['cid'];
$arr[$row['id']]['category_name'] = $row['category_name'];
$arr[$row['id']]['category_image'] = $row['category_image'];
$SQL1 = "SELECT * FROM tbl_sub_category WHERE cat_id = '".$arr[$row['id']]['cid']."'";
$result1 = mysql_query($SQL1);
while ($row1 = mysql_fetch_assoc($result1)) {
$temp = array('sub_cat_id' => $row1['sub_cat_id'], 'sub_cat_name' => $row1['sub_cat_name']);
$arr[$row['id']]['cats'][] = $temp;
}
}
$base_out = array();
foreach ($arr as $key => $record) {
$base_out['ShopApp'][] = $record;
}
$json = json_encode($base_out);
echo $json;
答案 0 :(得分:0)
在我看来,你只需要这样做:
$base_out['ShopApp'] = $arr;
答案 1 :(得分:0)
终于解决了自己
$SQL1 = "SELECT cid,category_name,category_image FROM tbl_category";
$result1 = mysql_query($SQL1);
$arr = array();
while ($row1 = mysql_fetch_assoc($result1))
{
$catArr=array();
$catArr['cid'] = $row1['cid'];
$catArr['category_name'] = $row1['category_name'];
$catArr['category_image'] = $row1['category_image'];
$SQL2 = "SELECT * FROM tbl_sub_category WHERE cat_id = '".$row1['cid']."'";
$result2 = mysql_query($SQL2);
$subcatArr=array();
while ($row2 = mysql_fetch_assoc($result2))
{
$temp = array('sub_cat_id' => $row2['sub_cat_id'], 'sub_cat_name' => $row2['sub_cat_name']);
$subcatArr[]=$temp;
}
$catArr['subcat']=$subcatArr;
$arr[$row1['cid']]=$catArr;
}
$shop_out = array();
foreach ($arr as $key => $record) {
$shop_out['ShopApp'][] = $record;
}
header( 'Content-Type: application/json; charset=utf-8' );
$json = json_encode($shop_out);
echo $json;