2013-10-16 62 views
4

我试图从获得的JSON获取单个值导致试图获取JSON结果

{ 
    "_total": 1, 
    "values": [{ 
    "id": 123456, 
    "name": "Example Technologies " 
    }] 
} 

现在,我需要得到_total值。对于我使用

echo $res->_total; 

这给了我 Notice: Trying to get property of non-object 如果我尝试像 echo $res['_total']; 给我

Warning: Illegal string offset '_total' 

那么,以什么方式,我可以得到_total值。

请帮助我。提前致谢!

+0

为了澄清这一点你$ res只是包含一个字符串值,这恰好是在JSON格式。这解释了你所得到的错误。 – bouscher

+0

PHP不直接与JSON字符串..你需要json_decode()它们以便有php对象/数组并且使用它。 – Svetoslav

回答

1

假设数据是

$data = '{"category_id":"10","username":"agent1","password":"82d1b085f2868f7834ebe1fe7a2c3aad:fG"}'; 

和你想获得特定参数,然后

$obj = json_decode($data); 

after 
$obj->{'category_id'} , $obj->{'username'} , $obj->{'password'} 

可能是这样的帮助你!

+0

但数据是'{ “_Total”:1, “值”:[{ “ID”:123456, “名”: “示例技术” }] }' - 那么,为什么假设别的东西吗? – davidkonrad

2

这样做:

$obj = json_decode($res); 
echo $obj->_total; 

您需要的JSON数据进行解码。

1

看来你没有json_decode()这个JSON字符串,或者$res不是json_decode()的结果。

例子:

$json = '{ 
    "_total": 1, 
    "values": [{ 
    "id": 123456, 
    "name": "Example Technologies " 
    }] 
}'; 

$res = json_decode($json); 

echo $res->_total; 
1

您将需要通过运行字符串json_decode第一http://uk3.php.net/json_decode 它会返回一个数组。

+0

'json_decode()'默认返回一个对象。您必须将第二个参数作为“TRUE”传递才能返回数组。 –

0

这里是你的字符串,

$data = '{ "_total": 1, "values": [{ "id": 123456, "name": "Example Technologies " }] }'; 
$test = (array)json_decode($data); 
echo '<pre>'; 
print_r(objectToArray($test)); 
die; 

功能在这里

function objectToArray($d) { 
     if (is_object($d)) { 
      // Gets the properties of the given object 
      // with get_object_vars function 
      $d = get_object_vars($d); 
     } 

     if (is_array($d)) { 
      /* 
      * Return array converted to object 
      * Using __FUNCTION__ (Magic constant) 
      * for recursive call 
      */ 
      return array_map(__FUNCTION__, $d); 
     } 
     else { 
      // Return array 
      return $d; 
     } 
    } 

可能是它的帮助你!