如何筛选数组条目
Array
(
[0] => A
[1] => A
[2] => A
[3] => B
[4] => A
[5] => B
)
etc....
我想得到这个结果
Array
(
[0] => A
[1] => B
[2] => A
[3] => B
)
我需要删除重复的secquence
答案 0 :(得分:0)
使用array_filter()非常简单,只需将每个值与前一个值进行比较
$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);
答案 1 :(得分: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
,并且您希望它保持它在多次调用函数时的值。