多维jsonphp

Multidimensional json php

如何在 JSON 文件中 select 特定条目?

   {
  "status" : "success",
  "data" : {
    "items" : [
      {
        "market_hash_name" : "AK-47 | Redline (Field-Tested)",
        "total_items" : 923,
        "lowest_price" : "4.00",
        "highest_price" : "300.00",
        "cumulative_price" : "8722.77",
        "recent_sales_info" : {
          "hours" : "18.07",
          "average_price" : "4.21"
        }
      },
      {
        "market_hash_name" : "AK-47 | Redline (Minimal Wear)",
        "total_items" : 51,
        "lowest_price" : "14.26",
        "highest_price" : "100.00",
        "cumulative_price" : "1089.71",
        "recent_sales_info" : {
          "hours" : "23.37",
          "average_price" : "14.36"
        }
      }
    ]
  }
}

截图:

我的PHP脚本:

$steam = "AK-47 | Redline (Field-Tested)";
$link = 'list.json';
    $string = file_get_contents($link);
    $obj = json_decode($string);
    if($obj->{'status'} == "success") die("notfound");
    $lowest_price = $obj->{'lowest_price'};
    $lowest_price[strlen($lowest_price)] = 0;
    echo $lowest_price;

我怎样才能 select 例如 Ak-47 Redline(经过现场测试)的 "total_items" 和 "average Price"? market_hash_name 保存在一个变量中,我想在其他变量中保存相关值。

谢谢。 最诚挚的问候。 恩格

使用json_decode和foreach你可以实现你想要的。

Online Check,检查并告诉我。

$json = '{
  "status" : "success",
  "data" : {
    "items" : [
      {
        "market_hash_name" : "AK-47 | Redline (Field-Tested)",
        "total_items" : 923,
        "lowest_price" : "4.00",
        "highest_price" : "300.00",
        "cumulative_price" : "8722.77",
        "recent_sales_info" : {
          "hours" : "18.07",
          "average_price" : "4.21"
        }
      },
      {
        "market_hash_name" : "AK-47 | Redline (Minimal Wear)",
        "total_items" : 51,
        "lowest_price" : "14.26",
        "highest_price" : "100.00",
        "cumulative_price" : "1089.71",
        "recent_sales_info" : {
          "hours" : "23.37",
          "average_price" : "14.36"
        }
      }
    ]
  }
}';
$result = json_decode ($json);

foreach($result->data->items as $val){
    if($val->market_hash_name == "AK-47 | Redline (Field-Tested)")
        echo "Total Item: ".$val->total_items." AND Avg Price:".$val->recent_sales_info->average_price;
    }       
}

结果是: 总项目:923 AND 平均 Price:4.21