How to find missing values in a sequence with PHP?

后端 未结 3 932
甜味超标
甜味超标 2021-01-21 14:02

Suppose you have an array \"value => timestamp\". The values are increasing with the time but they can be reset at any moment.

For example :

$array = arr         


        
相关标签:
3条回答
  • 2021-01-21 14:42

    You can do the following:

    • Keep comparing adjacent array keys. If they are consecutive you do nothing.
    • If they are not consecutive then you check their values, if the value has dropped from a higher value to a lower value, it means there was a reset so you do nothing.
    • If the value has not dropped then it is a case of missing key(s). All the numbers between the two keys(extremes not included) are part of the result.

    Translated in code:

    $array = array( 1 => 6000, 2 => 7000, 3 => 8000, 7 => 9000, 8 => 10000, 
                    9 => 11000,55 => 1000, 56 => 2000, 57 => 3000, 59 => 4000, 
                    60 => 5000,);
    
    $keys = array_keys($array);
    for($i=0;$i<count($array)-1;$i++) {
      if($array[$keys[$i]] < $array[$keys[$i+1]] && ($keys[$i+1]-$keys[$i] != 1) ) {
               print(implode(' ',range($keys[$i]+1,$keys[$i+1]-1)));
               print "\n";
       }   
    }
    

    Working link

    0 讨论(0)
  • 2021-01-21 14:44

    Here’s another solution:

    $prev = null;
    $missing = array();
    foreach ($array as $curr => $value) {
        if (!is_null($prev)) {
            if ($curr > $prev+1 && $value > $array[$prev]) {
                $missing = array_merge($missing, range($prev+1, $curr-1));
            }
        }
        $prev = $curr;
    }
    
    0 讨论(0)
  • 2021-01-21 14:58

    This gives the desired result array(4,5,6,58):

    $previous_value = NULL;
    $temp_store = array();
    $missing = array();
    $keys = array_keys($array);
    
    for($i = min($keys); $i <= max($keys); $i++)
    {
        if(!array_key_exists($i, $array))
        {
            $temp_store[] = $i;
        }
        else
        {
            if($previous_value < $array[$i])
            {
                $missing = array_merge($missing, $temp_store);
            }
            $temp_store = array();
            $previous_value = $array[$i];
        }
    }
    
    var_dump($missing);
    

    Or just use Gumbo's very smart solution ;-)

    0 讨论(0)
提交回复
热议问题