2016-03-05 54 views
0

如何能过滤出数组项如何过滤出数组条目?

Array 
(
    [0] => A 
    [1] => A 
    [2] => A 
    [3] => B 
    [4] => A 
    [5] => B 
) 
etc.... 

我想获得这样的结果

Array 
    (
     [0] => A 
     [1] => B 
     [2] => A 
     [3] => B 
    ) 

,我需要使用array_filter(),只是比较每个值删除重复secquence

+2

你有没有试过解决这个问题? – Rizier123

回答

0

如果你想这样做,作为一个人,这个过程很简单:

  • 看当前值。
  • 检查最后一个值。
  • 如果它们匹配,请将其删除。

使用代码的过程是一样的:

//the initial data 
$test = ["A", "A", "A", "B", "A", "B"]; 

//remember the last value 
$last = null; 

foreach($test as $key => $value){ 
    //is there a last value? does it match the current value? 
    if($last AND $last == $value){ 
     //then remove it 
     unset($test[$key]); 
     continue; 
    } 

    //remember the last value 
    $last = $value; 
} 

var_dump($test); 

输出:

array(4) { 
    [0] => 
    string(1) "A" 
    [3] => 
    string(1) "B" 
    [4] => 
    string(1) "A" 
    [5] => 
    string(1) "B" 
} 

正如Mark points out可以使用array_filter()做同样的事情。

在你只需要声明$last变量as static,因为你只希望它是null第一次函数被调用这种情况下,你希望它保持它的价值在多次调用该函数。

0

很简单与前一个

$data = ['A','A','A','B','A','B']; 

$data = array_filter(
    $data, 
    function($value) { 
     static $previous = null; 
     $return = $value != $previous; 
     $previous = $value; 
     return $return; 
    } 
); 

var_dump($data); 

Demo