2014-09-29 38 views
1

我想通過json_decode()從這個解碼字符串獲取country_id和country_name的值,但它不工作我的解碼數據是由print_r()引發的,如下所示:如何在codeigniter中將數組從視圖發佈到控制器

{"country_Data": 
       [ 
        {"country_id":"1","country_name":"India"},   

        {"country_id":"2","country_name":"Saudi Arabia"}, 

        {"country_id":"3","country_name":"UAE"} 
       ] 
} 

我試圖像 foreach($data['country_Data'][0]['country_id']) 但事先沒有luck.please幫助謝謝

回答

1

使用for循環這樣

$data = json_decode($json_data, true); // 2nd param converts output to associative arrays 

foreach($data['country_Data'] as $country_data) { 
    print_r($country_data); 
    echo $country_data['country_id'] .', '. $country_data['country_name']; 
} 
+0

參數無效。它給錯誤 – 2014-09-29 10:45:57

+0

我已經顯示的代碼假定你有適當的$數據數組。使用json_decode獲取$ data然後嘗試使用print_r打印它。 – Josnidhin 2014-09-29 10:47:40

1

您是先解碼$ data json嗎?

$data = json_decode($json) 

foreach($data['country_Data'] as $row) { 
    print_r($row); 
} 
+0

爲foreach()提供的參數無效。它給出了錯誤 – 2014-09-29 10:46:58

0

因爲json_decode從您的數據創建一個對象(默認),你需要進入電影它作爲一個屬性:

這樣的:

foreach($countryArray->country_Data as $row) { 
    echo $row->country_id; 
} 

或使用循環其他人建議但你需要確保json_decode返回一個數組,你可以設置第二個參數爲true,

$countryArray = json_decode($jsonString, true); 
1
//Your json encoded string 
$string = '{"country_Data": [{"country_id": "1","country_name": "India"},{"country_id": "2","country_name": "Saudi Arabia"},{"country_id": "3","country_name": "UAE"}]}'; 

//your data decoded in an array 
$arr = json_decode($string,true); 

foreach($arr as $item) 
{ 
     foreach($item as $value){ 
       print_r($value['country_id']." ".$value['country_name']."\n"); 
      } 

} 

//Printed data 
1 India 
2 Saudi Arabia 
3 UAE 

http://ideone.com/SmklSx

0

嘗試()提供的foreach此

$data = json_decode($json_data, true); 

foreach($data as $cd) { 
print_r($cd); 
echo $cd['country_id'] .', '. $cd['country_name']; 
} 
+0

我認爲當你爲你的內涵添加一些解釋時,它會對op和更多的訪問者有所幫助。 – reporter 2014-09-29 12:07:24

0
`$data = '{"country_Data":[{"country_id":"1","country_name":"India"}, 
      {"country_id":"2","country_name":"Saudi Arabia"}, 
      {"country_id":"3","country_name":"UAE"}]}'; 

$json = json_decode($data,true); 
foreach($json as $res) 
{ 
    foreach($res as $key => $value) 
    { 
     $datavalue[]=$value; 
    } 
} 
//print_r($datavalue); 
foreach($datavalue as $v) 
{ 
    echo $v['country_name'].'<br />'; 
} 

`

相關問題