我使用 json_decode
Php 函数获取国家/地区数据的 JSON 数组。
{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
},
如果我想检索第一个元素的代码,我可以这样做:
$result = json_decode($sXML);
$final = $result->Countries[0]->Name;
$final
的值为“Andorre”。
但是,如果我想使用相应的代码检索相同的值“Andorre”怎么办?
可以吗?
我知道 json_function()
有一个选项可以获取关联数组而不是 JSON 数组,但是您将如何使用它通过其代码获取值“Andorre”?
谢谢
最佳答案
<?php
$s = '{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$arr = json_decode($s, true);
print_r(array_column($arr['Countries'], "Name", "Code"));
?>
产量
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
关于php - 使用 JSON 数组中的 Php 如何根据另一个关联值检索项目的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572533/