K
K
kr_ilya2018-09-16 19:55:17
PHP
kr_ilya, 2018-09-16 19:55:17

How to calculate difference between values ​​in JSON?

We have a data.json file with the following content

[
 ["11.09.2018","222"],
 ["12.09.2018","392"],
 ["13.09.2018","485"],
 ["14.09.2018","449"],
 ["15.09.2018","449"],
 ["16.09.2018","467"]
]

How to calculate difference between next and previous value? (subtract 222 from 392) and put the results in another file as:
[
 ["1","170"], //392-222
 ["2","93"], //485-392
И так далее

And all this in PHP...
But before that, directly get the value of the data.json file like this
$file = file_get_contents('data.json');
$list = json_decode($file,TRUE);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2018-09-16
@kr_ilya

$data = json_decode($data);
$data = array_column($data, 1);
 
$result = [];
for($i = 1, $size = count($data); $i < $size; ++$i) {
  $result[$i] = $data[$i] - $data[$i - 1];
}
https://ideone.com/ZGf0iR

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question