PHP - 如何像处理数组一样解析对象的属性

3
我有以下的JSON对象:
$json = '{
"Name": "Peter",
"countries": {
    "France": {
        "A": "1",
        "B": "2"
    },
    "Germany": {
        "A": "10",
        "B": "20"
    },
    ....
}
}';

我希望能够像解析数组一样解析属性 "countries" 中对象的属性。在Javascript中,我会使用lodash函数values。在PHP中是否有类似的函数可以轻松实现?


1
json_decode http://php.net/manual/zh/function.json-decode.php - Colin Schoen
3个回答

4

这可能是一个重复问题。

以下是您需要的内容:

$array = json_decode($json, true);

json_decode解析json对象。true选项告诉它返回一个关联数组而不是对象。

要特别访问国家信息:

foreach ($array["countries"] as $ci) {
     //do something with data
}

请参考以下手册了解更多信息: http://php.net/manual/zh/function.json-decode.php 编辑以添加另一个答案中的好建议: 如果您需要国家名称,可以使用foreach访问键和值。请看下面的示例:
foreach ($array["countries"] as $country => $info) {
     //do something with data
}

2
你可以使用json_decode将字符串解析为JSON格式,并使用对象表示法,如下所示:
$countries = json_decode($json)->countries;
//do anything with $countries

你确定你代码的这一部分是正确的吗:$json->json_... - Jeff
@Jeff 哎呀!谢谢! - Aniket Sahrawat
"countries" 不是一个数组,而是一个对象。我做了以下操作:$data = json_decode($json, true);foreach ($data["countries"] as $info) { - MrScf
1
如果您使用json_decode($json, true),那么您将得到一个关联数组,因此您可以使用echo $info['A'] - Aniket Sahrawat

1

array_keys 和 Lodash 的 _.values 基本上做的是相同的事情。

$obj = json_decode($json, true); // cause you want properties, not substrings :P
$keys = array_keys($obj['countries']);

// $keys is now ['France', 'Germany', ...]

在PHP中,你可以同时获取键和值。
foreach ($obj['countries'] as $country => $info) {
    // $country is 'France', then 'Germany', then...
    // $info is ['A' => 1, 'B' => 2], then ['A' => 10, 'B' => 20], then...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接