2

我有这样的数组

{
0: "abc"
1: "abc"
5: "abc"
6: "def"
7: "ghk"
8: "abc"
}

我想删除相邻的相似值。就如

{
0: "abc"
6: "def"
7: "ghk"
8: "abc"
}

我尝试使用

$p = array_unique($array);

但它变成

{
0: "abc"
6: "def"
7: "ghk"
}

我不想删除 8: "abc" 因为它不是相邻的相似值。
我可以使用任何功能来做到这一点吗?谢谢 :)

4

2 回答 2

5
$myArray = array(
    0 => "abc",
    1 => "abc",
    5 => "abc",
    6 => "def",
    7 => "ghk",
    8 => "abc",
);

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

var_dump($newArray);
于 2013-04-03T13:21:12.073 回答
2

你可以这样做:

$myArray = array(
        0 => "abc",
        1 => "abc",
        5 => "abc",
        6 => "def",
        7 => "ghk",
        8 => "abc",
);

$newArray = array();
$previous = '';
foreach ($myArray as $myArray_value) {

    if ($previous !== $myArray_value)
        $newArray[] = $myArray_value;

    $previous = $myArray_value;

}

print_r($newArray);

希望这可以帮助你:)

于 2013-04-03T13:27:09.753 回答