如何从php中的json响应获取特定值

时间:2013-06-28 07:13:05

标签: php json

我的Json String看起来像这样:

现在我只想将ID的值作为整数:

[{"Obj" :    
        { "ID":"11",
          "NAME":"XYZ",
          "GENDER":"M" 
        }
}]

我该怎么做?

3 个答案:

答案 0 :(得分:2)

试试这个,

<?php
    $json='[{"Obj" :    
            { "ID":"11",
              "NAME":"XYZ",
              "GENDER":"M" 
            }
    }]';
    $jsonArray=json_decode($json);
    echo $jsonArray[0]->Obj->ID;
?>

答案 1 :(得分:2)

假设你的json字符串在post参数中:

$json_string = $_POST['json'];

使用json_decode可以将json字符串转换为php对象:

$json = json_decode($json_string);

然后访问您的ID:

$id = $json[0]->Obj->ID;

如果要将对象转换为关联数组,请执行以下操作:

$json = (array)$json;

并访问您的ID:

$id = $json[0]['Obj']['ID'];

答案 2 :(得分:1)

使用json_decode解码json输出,并将true作为第二个参数。它会给你数组输出。

$arr = json_decode($json,true);
echo $arr[0]['Obj']['ID'];
相关问题