如何在codeigniter中将数组从视图发布到控制器

时间:2014-09-29 10:25:42

标签: php arrays codeigniter

我想通过json_decode()从此解码字符串访问country_id和country_name的值但是它不能正常工作我的解码数据是由print_r()引用的,如下所示:

{"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']) 但没有运气。请事先帮助谢谢

6 个答案:

答案 0 :(得分: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'];
}

答案 1 :(得分:1)

您是否先解码$ data json?

$data = json_decode($json)

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

答案 2 :(得分: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

答案 3 :(得分:0)

因为json_decode从您的数据创建一个对象(默认情况下),您需要将其作为属性访问:

像这样:

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

或使用其他人建议的循环,但你需要确保json_decode返回一个数组,你可以这样设置第二个参数为true,

$countryArray = json_decode($jsonString, true);

答案 4 :(得分:0)

试试这个

$data = json_decode($json_data, true); 

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

答案 5 :(得分: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 />';
 }

`