Stack Exchange
Replace array element with last non zero value
I have a result array like the following :
Array
(
    [2013-02-27] => Array
        (
            [CPD] => 0
            [Display] => 0
            [Incent] => 0
            [Organic] => 1464
            [uncategorized] => 0
            [total] => 0
        )

    [2013-02-26] => Array
        (
            [CPD] => 0
            [Display] => 0
            [Incent] => 0
            [Organic] => 1463
            [uncategorized] => 0
            [total] => 0
        )

    [2013-02-25] => Array
        (
            [CPD] => 0
            [Display] => 0
            [Incent] => 0
            [Organic] => 1459
            [uncategorized] => 0
            [total] => 0
        )

    [2013-02-24] => Array
        (
            [CPD] => 0
            [Display] => 2
            [Incent] => 0
            [Organic] => 1449
            [uncategorized] => 0
            [total] => 0
        )

This is basically a running total thing and I need to have the zero values replaced by the higher value if there is any. I mean I have 2 as the count for 2013-02-24 for Display. So I need to have this has to be the count for other dates for display category. For making things a little more clear, this is the number of downloads for a product and I am calculating the count upto each day from various sources. So if it has a count of 2 upto 24th, it has to be the same upto the coming days if there the downloads for the day is zero. If downloads happen again it will added up. So what I am doing is I am looping the array and checking for zero values. If the value is zero for a particular section say Display, it has to be replaced with the higher number from the previous date if there is any. So how can I do this  ?
I have used the following code :
foreach ($result as $key=>$value){
            foreach($categories as $cat){
                if($value[$cat->category]==0){
          $prev_day = date("Y-m-d",strtotime ( '-1 day' , strtotime ( $key ) )) ;
          while ($prev_day>=$from) {
            if($result[$prev_day][$cat->category]!=0){
              $prev_high_value[$cat->category]=$result[$prev_day][$cat->category];
              break;
            }
            $prev_day = strtotime ( '-1 day' , strtotime ( $prev_day ) ) ;
          }
          $result[$key][$cat->category]=$prev_high_value[$cat->category];
            }
        }
    }

where $category is an object with the category values like Display an others

What have you tried?

I first tried to go to get the value for previous date and assign it. But it will not work as there will not be any values when we are iterating.

I have edited with the code that I have done. But this is giving wrong results
