Php数组-不能从数组中获取值


Php array - can't get value from array

$data = '{"name":"CocaCola","price":1,"sync":0,"id":10792}';
$data = json_decode($data);
print_r((array)$data);
//Array ( [name] => CocaCola [price] => 1 [sync] => 0 [id] => 10792 )
print_r((array)$data["id"]);
//nothing?

这段代码对我来说不是逻辑。我能得到任何解释这种行为和如何解决它?

(array)$data["id"]

作为

执行
(array)($data["id"])

$data['id']的结果被强制转换为数组;非$data强制转换为数组,然后访问其id索引。

如果你想要一个数组,使用json_decode(..., true)。否则,将对象作为对象使用,而不是一直将它们转换为数组。

json_decode返回具有属性的对象,而不是数组。

http://uk3.php.net/json_decode

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

将true (bool值)传递给json_decode函数中的第二个参数,以返回关联数组。然后你就可以把它作为一个数组来访问了。

或者,可以使用->操作符访问属性。

所以在你的例子中:

print_r($data->id);

你不能这么做

print_r((array)$data["id"]);

尝试相反

$d = (array)$data;
print_r($d["id"]);

使用json_decode返回一个对象(例如:数据-> id)。
如果您希望它返回一个数组,请使用json_decode($data, true);