1

I have an array of temperature data by hour. Some hours have zero data instead of a temp. When graphing using Google Charts, the zero causes the line graph to plummet. My temporary fix was to replace the zero values with null, causing a break in the line graph. The ideal solution would be to take the values on either side of the zero, and average them. The array is in order by hour. Help?

$array = array(
    "1AM" => "65",
    "2AM" => "66",
    "3AM" => "68",
    "4AM" => "68",
    "5AM" => "68",
    "6AM" => "0",
    "7AM" => "70",
    "8AM" => "71",
    "9AM" => "71",
    "10AM" => "73",
);

Here's my script replacing the 0's with nulls:

  $array = array ();
  foreach($parsed_json->history->observations as $key => $value) {
    $temp = (int)$value->tempi;
    if ($temp==0) {
        str_replace(0, null, $temp);
    }
    $hour = $value->date->hour;
    $array[$hour] = $temp;
  };

This Example would work great if the data was mine, but alas, it's from a JSON feed.

Would I use an array_walk() sort of deal? How would I reference the current place in the array? Any help is appreciated!

Community
  • 1
  • 1
Dean Grell
  • 143
  • 8

3 Answers3

2

I would scratch out the null portion, and just foreach-loop through the final array.

So, change your current code to:

$array = array ();

foreach($parsed_json->history->observations as $key => $value) {
    $temp = (int)$value->tempi;
}

$hour = $value->date->hour;
$array[$hour] = $temp;

And add this below it:

foreach($array as $hour => $temp){

  if($temp == "0"){
      $numHour = $hour[0];
      $hourPlus  = ($numHour + 1) . "AM";
      $hourMinus = ($numHour - 1) . "AM";

      $valuePlus  = $array[$hourPlus];
      $valueMinus = $array[$hourMinus];

      $average = ($valuePlus + $valueMinus)/2;

      $array[$hour] = $average;
  }

}
?>

This of course assumes that the values on either side of the zero are also not zero. You may want to add a check for that somewhere in there.

Tested and proven method.

VictorKilo
  • 1,839
  • 3
  • 24
  • 39
  • It worked! Thanks! Other days have PM's as well, but I think I have that figured out. Also put a check in for consecutive zeros, and if it's a zero at the end or start of the array. Thanks! – Dean Grell Aug 02 '12 at 17:33
  • Sweet, glad it worked for you! Yeah, you can account for the AM or PM fairly easily. – VictorKilo Aug 02 '12 at 18:38
0

Couldn't you do something along the lines of:

str_replace(0, ((($key-1)+($key+1))/2), $temp);

Where $key is array position, take the value before 0 and after 0 add them and divide them by 2 to get the average.

Event_Horizon
  • 708
  • 1
  • 11
  • 30
0

I'll let you sort out what happens if first, last or consecutive values are 0.

$the_keys=array_keys($array);
foreach($the_key as $index=>$key)
{
    if($array[$key]==0)
    {
        $array[$key]=($array[$the_key[$index-1]]+$array[$the_key[$index+1]]/2);
    }
}
Waygood
  • 2,657
  • 2
  • 15
  • 16