有条件地从数组中删除相邻的重复项

时间:2018-06-14 04:44:40

标签: php arrays

我有以下代码可以删除$myArray

中的相邻重复项
<?php
 $myArray = array(
                    0 => 0,
                    1 => 0,
                    2 => 1,
                    5 => 1,
                    6 => 2,
                    7 => 2,
                    8 => 2,
                    9 => 0,
                    10 => 0,
                );

            $previtem= NULL;
            $newArray = array_filter(
                $myArray,
                function ($currentItem) use (&$previtem) {
                    $p = $previtem;
                    $previtem= $currentItem;
                    return $currentItem!== $p ;
                }
            );

echo "<pre>";
print_r($newArray);
?>

它完全正常,但我必须更改值2的条件位。这意味着对于其他值,我们可以先选择并忽略其他值。但对于2,我们需要选择最后一次出现并忽略其他事件。

所需的输出是

Array
(
    [0] => 0 //first occurrence of 0 in $myArray
    [2] => 1 //first occurrence of 1 in $myArray
    [8] => 2 //last occurrence of 2 in the $myArray
    [9] => 0 //first occurrence of 0 in $myArray
)

如何修改我的代码以达到上述效果?

实际上我有多维数组,但为了更好的解释,我在问题中使用了单维数组。

更新 我的实际数组是

$myArray = array(
        0 => array("Value"=>0, "Tax" => "11.00"),
        1 => array("Value"=>0, "Tax" => "12.00"),
        2 => array("Value"=>1, "Tax" => "13.00"),
        5 => array("Value"=>1, "Tax" => "14.00"),
        6 => array("Value"=>2, "Tax" => "15.00"),
        7 => array("Value"=>2, "Tax" => "16.00"),
        8 => array("Value"=>2, "Tax" => "17.00"),
        9 => array("Value"=>0, "Tax" => "18.00"),
        10 => array("Value"=>0, "Tax" => "19.00"),
    );

我的实际代码

$previtem= NULL;
$newArray = array_filter(
    $myArray,
    function ($currentItem) use (&$previtem) {
        $p["Value"] = $previtem["Value"];
        $previtem["Value"] = $currentItem["Value"];
        return $currentItem["Value"]!== $p["Value"] ;
    }
);

由于

2 个答案:

答案 0 :(得分:1)

这应该可以满足您的需求。

function array_filter($a) {
$na = array();
$first = true;
$p = null;
$wantlast = false;
foreach ($a as $v) {
    if ($wantlast) {
        ($v != $p) ? $na[] = $p: null;
    }
    $wantlast = ($v == 2) ? true : false;
    if (!$wantlast) {
        (($v != $p) || ($first))? $na[] = $v : null;
    }
    $p = $v;
    $first = false;
}
return $na;
}

答案 1 :(得分:1)

$myArray = array(
        0 => 0,
        1 => 0,
        2 => 1,
        5 => 1,
        6 => 2,
        7 => 2,
        8 => 2,
        9 => 0,
        10 => 0,
    );

$previtem= NULL;
$newArray = array_filter(
    $myArray,
    function ($currentItem, $key) use (&$previtem,$myArray) {
        $p = $previtem;
        if($currentItem != 2){
            $previtem = $currentItem;
        }else{
            $lastkey = array_search(2,(array_reverse($myArray, true)));
            if($key != $lastkey)
                $currentItem = $previtem;
        }
        return $currentItem!== $p ;
    }, ARRAY_FILTER_USE_BOTH
);

echo "<pre>";
print_r($newArray);