2016-03-14 74 views
-1

我想用類別和子類別爲我的應用程序嵌套JSON,這是我的代碼PHP嵌套的類別和子類別JSON

// get all items from myorder table 
$result = mysql_query("SELECT co.country, cl.city_code, cl.city_name 
         FROM country as co, city_list as cl 
         WHERE co.id_country = cl.id_country") or die(mysql_error()); 

$response["location"] = array(); 

while ($row = mysql_fetch_assoc($result)) { 
    $categories['Cities'][] = array(
      'code'   => $row['city_code'], 
      'city'   => $row['city_name'], 
    ); 
} 

foreach ($categories as $key => $value) { 
    $category_data[] = array(
     'category'  => $key, 
     'category_list' => $value, 
    ); 
} 

array_push($response["location"], $categories); 
// echoing JSON response 
echo json_encode($response); 

,這是結果:

{ 
location: [ 
    { 
     USA: { 
      Country: "USA" 
      Cities: [ 
       { 
        code: "AL", 
        city: "ALABAMA" 
       }, 
       { 
        code: "AR", 
        city: "Arkansas" 
       }, 
       { 
        code: "DC", 
        city: "Distric of Columbia" 
       }, 
       { 
        code: "LA", 
        city: "Louisiana" 
       } 
       ] 
      } 
     } 

    ] 
} 

我想要得到這種格式:

{ 
location: [ 
    Country: "USA" 
    Cities: [ 
     { 
      code: "AL", 
      city: "ALABAMA" 
     }, 
     { 
      code: "AR", 
      city: "Arkansas" 
     }, 
     { 
      code: "DC", 
      city: "Distric of Columbia" 
     }, 
     { 
      code: "LA", 
      city: "Louisiana" 
     }, 


    ] 
} 

我該怎麼做到這一點?有沒有我可以研究的參考資料? 有幫助嗎?

+0

這是動態的「國家:」美國「? – aldrin27

+0

'co.country'是您的請求中的國家名稱? –

+0

yup,國家對象將列出幾個國家... yup,co.country將在過程中調用國家名稱... – meeftah

回答

0

首先,在您的請求中按國名排序。

while ($row = mysql_fetch_assoc($result)) { 
    if (! isset($categories[$row['country']])) { 
      $categories[$row['country']] = array('Country' => $row['country']); 
      $categories[$row['country']]['Cities'] = array(); 
    } 

    $categories[$row['country']]['Cities'][] = array(
     'code'   => $row['city_code'], 
     'city'   => $row['city_name'], 
    ); 

} 

... rest of your code 

順便說一下,你應該停止使用mysql_ *函數並使用mysqli_ *。正如寫在SO上的每一篇文章..

+0

請在我的更新後的帖子中看到結果,我用你的代碼得到了結果...我在這之後會用mysqli改變mysql;) – meeftah