major697
major697

Reputation: 1862

assign the youngest and oldest value from JSON in PHP

...
  [188]=>
  array(4) {
    ["id"]=>
    string(4) "1201"
    ["coins_id"]=>
    string(2) "22"
    ["price"]=>
    string(8) "11.42033"
    ["time"]=>
    string(19) "2018-04-19 09:45:56"
  }
...
  [534]=>
  array(4) {
    ["id"]=>
    string(4) "9391"
    ["coins_id"]=>
    string(2) "22"
    ["price"]=>
    string(8) "17.87132"
    ["time"]=>
    string(19) "2018-04-19 10:09:17"
  }
...

I want to calculate the percentage difference in the price, however I do not know how to assign the youngest and the oldest value to variables. In this json, always the older value has a smaller id. The common value is coins_id.

$price_young = //price with id = 534;
$price_old = //price with id = 188;
$percent_diffrent = (1 - $price_old / $price_young) * 100;

Upvotes: 1

Views: 68

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You can use max() and min() along with array_column()

$price_array = array_column($array,'price'); // get all prices in an array

$price_young = (float)max($price_array); // get max latest price
$price_old = (float)min($price_array); // get min old price
$percent_diffrent = (1 - $price_old / $price_young) * 100;

A hard-coded example:- https://eval.in/990963

Upvotes: 1

Related Questions