0

I am new to code, I am trying to pull certain JSON API with PHP. In this case it is ETH_USD. Below is a snippet of the API.

{"symbol":"ETH_USD","volumen24hours":398.18320159,"ask":235.9,"bid":212.50000001,"lastPrice":213.48283633},{"symbol":"ETH_EUR","volumen24hours":101.79246082,"ask":191.51196436,"bid":191.51196436,"lastPrice":191.51196436},{"symbol":"ETH_ARS","volumen24hours":56.42036715,"ask":9365.12240119,"bid":8952,"lastPrice":9365.12240119},

Below is my php code until now. How do I just get the ETH_USD data? Any help is appreciated.

<?php

$url = "https://www.website.com/api/ticker?format=json";
$fgc = file_get_contents($ur);
$json = json_decode($fgc, true);

$price = $json["lastPrice"];
$high = $json["ask"];
$low = $json["bid"];
$open = $json["open"];

if($open < $price){
//price went up
    $indicator = "+"
    $change = $price - $open;
    $percent = $change / $open;
    $percent = $percent * 100;
    $percentChange = $indicator.number_format($percent, 2);
    $color = "green";
}
if($open > $price){
//price went down
    $indicator = "-"
    $change = $open - $price;
    $percent = $change / $open;
    $percent = $percent * 100;
    $percentChange = $indicator.number_format($percent, 2);
    $color = "red";
}
?>
MH2K9
  • 11,951
  • 7
  • 32
  • 49
Webdes
  • 11
  • 1
  • 1
    Possible duplicate of [How can I parse a JSON file with PHP?](https://stackoverflow.com/questions/4343596/how-can-i-parse-a-json-file-with-php) – aynber Jul 31 '19 at 16:44

1 Answers1

0

You could use array_filter for that purpose :

$json = '[{
    "symbol": "ETH_USD",
    "volumen24hours": 398.18320159,
    "ask": 235.9,
    "bid": 212.50000001,
    "lastPrice": 213.48283633
}, {
    "symbol": "ETH_EUR",
    "volumen24hours": 101.79246082,
    "ask": 191.51196436,
    "bid": 191.51196436,
    "lastPrice": 191.51196436
}, {
    "symbol": "ETH_ARS",
    "volumen24hours": 56.42036715,
    "ask": 9365.12240119,
    "bid": 8952,
    "lastPrice": 9365.12240119
}]';


$new = array_filter(json_decode($json, true), function ($var) {
    return ($var['symbol'] == 'ETH_USD');
});
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
  • Thanks for the quick response. I see that you added the json info: $json = '[{ "symbol": "ETH_USD", "volumen24hours": 398.18320159, "ask": 235.9, "bid": 212.50000001, "lastPrice": 213.48283633 My next question is if the json API is updated everyday, how do I keep it current. As the API url gets updated with new info everyday. Example.. the "lastPrice" numbers may change to higher number. – Webdes Jul 31 '19 at 18:35
  • It doesn't matter if the value gets updated since we only filter the `symbol` key which have `ETH_USD` value. But my question is you have `$open = $json["open"]`, but there are no `open` data on your json – Hasta Dhana Aug 01 '19 at 03:18