建立一間商店陣列,且menu裡擁有兩個餐點,最後轉為json格式
$store = "storeId" => 1, "storeName" => "Gary Bees", "storetel" => "07123456", "menu" => array( array( "menuId" => 01, "menuName" => "Hamburger" ), array( "menuId" => 02, "menuName" => "Beef" ) ), "is_open" => true ); $store_json = json_encode($store); echo $store_json;
json_encode涵式將我們的多維陣列轉換成以下的JSON格式
"storeId":1, "storeName":"Gary Bees", "storetel":"07123456", "menu":[{"menuId":1,"menuName":"Hamburger"}, {"menuId":2,"menuName":"Beef"}], "is_open":true }
更多運用,假設目前有兩間商店,並在menu裡頭各有兩份餐點。
$store = array( array( "storeId" => 1, "storeName" => "Gary Bees", "storetel" => "07123456", "menu" => array( array( "menuId" => 01, "menuName" => "Hamburger" ), array( "menuId" => 02, "menuName" => "Beef" ) ), "is_open" => true ), array( "storeId" => 2, "storeName" => "Tofu", "storetel" => "07123789", "menu" => array( array( "menuId" => 01, "menuName" => "Sandwiches" ), array( "menuId" => 02, "menuName" => "Pork" ) ), "is_open" => true )); $store_json = json_encode($store); echo $store_json; $store_dejson = json_decode($store_json); echo $store_dejson[0]->storetel; echo $store_dejson[1]->menu[0] -> menuName;以上可以由此類推更多的商店或更多menu,而最後decode已encode過的json字串看似多餘,不過可以更清楚這兩個涵式之間的運作哦!
沒有留言:
張貼留言