-1

I get temperature readings in the last hour. The data comes in the form of a line where data is displayed for every 10 minutes.

200504, 0530, 0, 262.3, 1.399, 6.097, 2.15, 
200504, 0540, 0, 251.2, 1.29, 6.08, 2.09,
200504, 0550, 0, 249.4, 1.685, 5.921, 2.44,
200504, 0600, 0, 249.5, 1.465, 5.904, 2.27,
200504, 0610, 0, 247.7, 1.801, 6.214, 2.61,
200504, 0620, 0, 246.9, 1.908, 6.532, 3.04,

It is necessary to calculate the average value of the last element of the row

$str = '190227, 2020, 9, 245.8, 2.886, 5.753, 0';

$pattern = '/([\S]*),\s([\S]*),\s([\S]*),\s([\S]*),\s([\S]*),\s([\S]*),\s([\S]*)/m';

preg_match($pattern, $str, $matches);

$result =  [
    "Date" =>  intval($matches[1]),
    "Time" =>  intval($matches[2]),
    "h" => intval($matches[3]),
    "Deg.M" => floatval($matches[4]),
    "m/s" => floatval($matches[5]),
    "deg.C" => floatval($matches[6]),
    "mm/h" => floatval($matches[7])
];

With this solution, I get data for one time interval, but how can I write all this data into one array and calculate the average value?

6
  • 3
    Use explode instead? Way more easy to do what you want. php.net/manual/en/function.explode.php Commented Jun 8, 2020 at 21:08
  • Split on ,\s+. Done. Commented Jun 8, 2020 at 21:10
  • Does this answer your question? Average result of multidimensional array in PHP Commented Jun 8, 2020 at 21:11
  • 200504, 0530, 0, 262.3, 1.399, 6.097, 2.15, is one line? or all your numbers in one line? ... from where you take the data? from a file .. or how they come.. you give to less explanations for your question.. and your example show just one line.. Commented Jun 8, 2020 at 21:21
  • @ChrisG Yes, an example for one line. Before that, I needed to process only one line. And now there are several at a time, and for this they need to be written into an array.The data comes as indicated in the example as a string. Commented Jun 8, 2020 at 21:54

1 Answer 1

0

You could treat it like a CSV (Comma Seperated File), which it actially is:

$lines = explode(PHP_EOL, $data);
$array = array_map('str_getcsv', $lines); 
print_r($array);

You might want to fancy it up a bit with a trim and some named keys, but this gets the bulk of the job done :)

Then, if you want all last values and sum/avg them:

$values = array_column($array, 6);
$avg = array_sum($values)/count($values);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.