Многомерный json php


Как я могу выбрать определенные записи в файле 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"
        }
      }
    ]
  }
}

Скриншот:

enter image description here

Мой 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;

Как я могу выбрать, например, "total_items" и "среднюю цену" Красной линии Ак-47 (проверено в полевых условиях)? Имя market_hash_name сохраняется в переменной, и я хочу сохранить в других переменных соответствующие значения.

Спасибо. С наилучшими пожеланиями. Энге

Author: Pratik Butani, 2016-05-18

1 answers

Используя json_decode и foreach, вы можете достичь того, чего хотите.

Онлайн-проверка, Проверьте и дайте мне знать.

$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, Средняя цена: 4,21

 0
Author: Frayne Konok, 2016-05-18 09:12:44