簡體   English   中英

PHP - 像對象一樣解析對象的屬性

[英]PHP - Parse properties of an Object like an Array

我有以下JSON對象:

$json = '{
"Name": "Peter",
"countries": {
    "France": {
        "A": "1",
        "B": "2"
    },
    "Germany": {
        "A": "10",
        "B": "20"
    },
    ....
}
}';

我想像屬性一樣解析屬性“countries”中對象的屬性。 在Javascript中我會使用lodash函數values 在PHP中有任何功能可以輕松完成嗎?

這可能是重復的。

這就是你需要的:

$array = json_decode($json, true);

json_decode解析一個json對象。 true選項告訴它返回一個關聯數組而不是一個對象。

要具體訪問國家/地區信息:

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

有關詳細信息,請參閱手冊: http//php.net/manual/en/function.json-decode.php

編輯以在另一個答案中添加一個好點:如果您還需要國家/地區名稱,則可以使用foreach訪問鍵和值。 像這樣:

foreach ($array["countries"] as $country => $info) {
     //do something with data
}

您可以使用json_decode將字符串解析為json並使用對象表示法,如下所示:

$countries = json_decode($json)->countries;
//do anything with $countries

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...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM