4

我正在尝试从获得的 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价值。

请帮助我。提前致谢!

4

5 回答 5

2

做这个:

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

您需要解码 JSON 数据。

于 2013-10-16T09:06:47.340 回答
1

假设数据是

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

然后你想获得特定的参数

$obj = json_decode($data);

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

可能对你有帮助!

于 2013-10-16T09:11:16.327 回答
1

看来您没有json_decode()JSON 字符串,或者$res不是json_decode().

例子:

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

$res = json_decode($json);

echo $res->_total;
于 2013-10-16T09:06:57.080 回答
1

您需要首先通过 json_decode 运行字符串http://uk3.php.net/json_decode ,这将返回一个数组。

于 2013-10-16T09:07:30.603 回答
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;
        }
    }

可能对你有帮助!!

于 2014-01-29T09:39:33.287 回答