通过值保留键折叠PHP数组元素(非唯一)

Ive worked on this so long that I must be over complicating a simple solution.

Given the following in arrays

    $in_num = array('a'=>1, 'b'=>1, 'c'=>2, 'd'=>1, 'e'=>2, 'f'=>2, 'g'=>2, 'h'=>2);  
    $in_str = array('a'=>'a', 'b'=>'a', 'c'=>'b', 'd'=>'a', 'e'=>'b', 'f'=>'b', 'g'=>'b);  

Desired output

    $out_num = array('a'=>1, 'c'=>2, 'd'=>1, 'e'=>2);   
    $out_str = array('a'=>'a', 'c'=>'b', 'd'=>'a', 'e'=>'b');  

The Key order must be maintained.

array('a'=>1, 'b'=>'str') does NOT occur.  

Sure would appreciate your help.

What you really want to know and preserve is the key/value pair that differs from the previous value. This can be done with a simple function

function collapse($array = array()) {
    //initialize the answer and previous value
    $ans = array();
    $prevValue = null;

    foreach($array as $key=>$val) {
        //we only care if the current $val is different than the previous $value
        if ($val != $prevValue) {
            $ans[$key] = $val;
        }
        //save the current value as the previousValue for the next iteration
        $prevValue = $val;
    }
    return $ans;
}

This will return what you are asking when called with collapse($in_num) or collapse($in_str).

<?php
$in_num = array('a'=>1, 'b'=>1, 'c'=>2, 'd'=>1, 'e'=>2, 'f'=>2, 'g'=>2, 'h'=>2);  

$previous = '';
foreach( $in_num as $k=> $v){

  if($v !=$previous){
    $out[$k]=$v;    
  }

$previous=$v;

}

print_r($out);

output:

Array
(
    [a] => 1
    [c] => 2
    [d] => 1
    [e] => 2
)