假设我有:
Data={Alex: {height: 6, weight: 160}, Rez: {height: 5.6, weight: 158}};
如何在不实现 php 中 foreach 方法的情况下访问 Rez 权重的值(权重:158)?
会不会是类似$_POST['Rez']['weight]
的东西?
假设您实际上在某处有一个有效的 JSON 字符串(即正确引用等),有两种方法可以将其解码为本机 PHP 数据结构:
进入嵌套对象:
$data = json_decode($json)
$rezWeight = $data->Rez->weight;
进入嵌套数组:
$data = json_decode($json, true);
$rezWeight = $data['Rez']['weight'];
使用这些方法中的任何一种,$rezWeight
变量最终将变为 158。重要的是,无论哪种情况,不,您都不需要实现循环。
对于PHP,你必须先解码JSON..但你的JSON看起来有点奇怪。
$data = '{"Alex":
{"height": "6", "weight": "160"},
"Rez":
{"height": "5.6", "weight": "158"}
}';
$array = json_decode($data, true);
$height = $array['Alex']['height'];