2017-06-21 34 views
0

我試圖解碼json並從json代碼中獲取值。如何在codeingiter中讀取json數組

[{ 
    "restaurant_id":1, 
    "menu_template_id":2, 
    "add_food_item_a":1, 
    "menu_category_id":1, 
    "status":0 
} , 
{ 
    "restaurant_id":1, 
    "menu_template_id":2, 
    "add_food_item_a":2, 
    "menu_category_id":1, 
    "status":0 
}] 

我需要從這個json中讀取數據並創建一個add_food_item_a和狀態的數組。

我目前使用這樣的

public function readJson() 
    { 
     $json_obj = json_decode(''); 
     if (isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"])) { 
      $json_text = $this->cleanMe($GLOBALS["HTTP_RAW_POST_DATA"]); 
      // now insert into user table 
      $json_obj = json_decode($json_text); 
     } 
     return $json_obj; 
    } 

,我喜歡叫

$add_food_item_a = isset($json_obj->add_food_item_a) ? $json_obj->add_food_item_a : ''; 

這個功能,但不能從這個數組的JSON代碼

+0

你嘗試過使用'json_decode'嗎? – FMashiro

+0

用戶json_decode($ your_array,true);然後使用foreach循環來移動關聯數組,然後您可以創建任何與可用關聯數組的保護區 – pAsh

+0

首先這是在API中,我無法觸及它。 – Midhun

回答

1

你想讀取'add_food_item_a'和'狀態'的值

<?php 

    $json='[{ 
     "restaurant_id":1, 
     "menu_template_id":2, 
     "add_food_item_a":1, 
     "menu_category_id":1, 
     "status":0 
    } , 
    { 
     "restaurant_id":1, 
     "menu_template_id":2, 
     "add_food_item_a":2, 
     "menu_category_id":1, 
     "status":0 
    }]'; 

    echo "<pre>"; 
    $array = json_decode($json,1); 
    print_r($array); 
    foreach($array as $value) 
    { 
     echo "\n".$value['add_food_item_a']; 
     echo "\n".$value['status']; 
    } 
+0

我的json代碼是郵遞員,我需要retreve作爲一個數組這是我的問題 – Midhun

+0

'json_decode($ json_text,1);'將1作爲參數傳遞給'json_decode'你會獲取數組 –

+0

,但顯示錯誤,如'Cannot使用stdClass類型的對象作爲數組' – Midhun