使用PHP在JSON中搜索值
我有一个类似上面的长json代码,我需要通过搜索“id”名称来获得“price_usd”值。使用PHP在JSON中搜索值,php,arrays,json,search,Php,Arrays,Json,Search,我有一个类似上面的长json代码,我需要通过搜索“id”名称来获得“price_usd”值。 我不想要$str[0][“node”][“price_usd”]只要在数组上迭代,当你点击时就可以中断: <?php $str = '[ { "node":{ "id": "bitcoin", "name": "Bitcoin&quo
我不想要$str[0][“node”][“price_usd”]只要在数组上迭代,当你点击时就可以中断:
<?php
$str = '[
{
"node":{
"id": "bitcoin",
"name": "Bitcoin",
"price_usd": "610.471"
}
},
{
"node":{
"id": "ethereum",
"name": "Ethereum",
"price_usd": "12.0771"
}
}
]';
$result = json_decode($str, true);
$key = array_search('bitcoin', array_column($result,'node','id'));
echo $result[$key]['price_usd']; // i need 610.471 here
?>
上面的代码假设每个子数组都有一个名为
节点
的键,该键还包含一个名为id
的键。如果你不能依赖这些东西,你需要在每次迭代中检查。我还假设您只需要一个值(第一个值),因为可能存在多个id
等于bitcoin
的实例。您可以使用双array\u column()
按id获取价格列表:
$prices\u by\u id=array\u列(array\u列($result,'node'),'prices\u usd,'id');
这是必需的,因为原始JSON字符串中有多个嵌套级别
$prices\u by\u id的值
:
foreach ($result as $k => $v) {
if ($v['node']['id'] == 'bitcoin') break;
}
echo $result[$k]['node']['price_usd'];
通过这种方式,您可以使用
$prices\u by_id['bitcoin']
获取其价格。与JSON解析无关,因为在搜索时,您不再使用JSON($str
)。
array(2) {
["bitcoin"]=>
string(7) "610.471"
["ethereum"]=>
string(7) "12.0771"
}