【问题标题】:Search a value in JSON using PHP使用 PHP 在 JSON 中搜索值
【发布时间】:2021-02-17 12:11:51
【问题描述】:
<?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

?>   

我有一个像上面这样的长 json 代码,我需要通过搜索“id”名称来获取“price_usd”值。 我不想要 $str[0]["node"]["price_usd"]

【问题讨论】:

  • 与 JSON 解析无关,因为在您搜索时,您不再使用 JSON ($str)。

标签: php arrays json search


【解决方案1】:

只需遍历数组并在遇到命中时中断:

foreach ($result as $k => $v) {
    if ($v['node']['id'] == 'bitcoin') break;
}
echo $result[$k]['node']['price_usd'];

上面的代码假定每个子数组都有一个名为node 的键,其中还包含一个名为id 的键。如果你不能依赖这些东西,你需要检查每次迭代。我还假设您只需要一个值(第一个),因为很容易有多个 id 实例等于 bitcoin

【讨论】:

    【解决方案2】:

    您可以使用双精度 array_column() 以通过 id 获取价格列表:

    $prices_by_id = array_column(array_column($result, 'node'), 'price_usd', 'id');
    

    这是必需的,因为原始 JSON 字符串中有多个嵌套级别。

    $prices_by_id的值:

    array(2) {
      ["bitcoin"]=>
      string(7) "610.471"
      ["ethereum"]=>
      string(7) "12.0771"
    }
    

    这样您就可以使用$prices_by_id['bitcoin'] 来获取它的价格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      相关资源
      最近更新 更多