我試圖搜索JSON文件中的值,並從同一對象返回不同的值。通過PHP中的JSON值檢索數據
的JSON看起來是這樣的:
{
"source": {
"name": "source1",
"url": "https://someurl",
"apiKey": "someapi"
},
"targets" : [
{
"name" : "target1",
"url": "https://target1url",
"apiKey": "target1api"
},
{
"name" : "target2",
"url": "https://target2url",
"apiKey": "target2api"
}
]
}
我想按名稱搜索來檢索 「apiKey」 值。我知道這可以通過foreach()
和if
聲明完成,但我無法獲得該值。我的PHP代碼是這樣的:
// get the json config file
$json = file_get_contents('config.json');
// decode the JSON
$config = json_decode($json, true);
foreach ($config["targets"] as $key => $value) {
if ($value->name == "target1") {
echo $value->apiKey;
}
}
將「名稱」與其他屬性放在同一級別是不好的做法嗎?例如,「名稱」應該是父母名稱,而其他值是子女?或者,如果JSON沒問題,你能幫我理解爲什麼上述不起作用嗎?
對不起忘了$配置申述//獲取JSON配置文件 $ JSON =的file_get_contents( 'config.json'); //解碼JSON $ config = json_decode($ json,true); – user1416876