0

I have an array that plucks values to an array like so:

        /* Pluck just the wattage values to an array */
        $realtime_data_array = $latestrtfeed->nth(60)->reverse()->pluck('data')->toArray();

which results in:

array:150 [▼
  0 => 20277.6
  1 => 20281.4
  2 => 20285.3
  3 => 20289.7
  4 => 20293.8
  5 => 20298.6
  6 => 20303.2
  7 => 20307.4
  8 => 20311.5
  9 => 20315.8
  10 => 20319.8

these value get inputted to the chart like so:

    $realtime_consumption_chart->dataset('kWh', 'line', $realtime_data_array);

The problem is that the sensor is storing cumulative values and I only want to show the difference between value 0 and value 1 then difference between value 1 and value 2 and so on and so on.

How would I go about something like that?

I am going to take a shot and say that I'm going to have to do a FOREACH on the array and create a new array with the values adjusted, but how do I go about that? maybe:

    foreach ($realtime_data_array as $data) {
        $realtime_data_array_corrected = ($data[1]-$data[0])->toArray();
    }

Nope there is something I'm doing wrong or not considering here.

1 Answer 1

1
for ($i = 0; $i < sizeof($realtime_data_array); $i++) {
    if($i==0) {
       $realtime_data_array_corrected[$i] = 0;
       continue;
    }
    $realtime_data_array_corrected[$i] = $realtime_data_array[$i] - $realtime_data_array[$i-1];
} 
Sign up to request clarification or add additional context in comments.

4 Comments

I get an error of: "Undefined offset: 150" on line" $realtime_data_array_corrected[$i] = $realtime_data_array[$i] - $realtime_data_array[$i-1]; " thank you so much by the way.
Maybe it's not taking into account that there wille be nothing to compare the last value to. If there are 150 value and the first one starts at 0 then the last value will be 149. There will be no 150 I suppose. That might be the issue here.
You are right, I edited the code, it should be < instead of <= in loop condition
If the code works as expected, you can accept the answer also :D

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.