-2

当前代码——

<?php
$arrunsort = array('ab','ad','ar','cd','cb','sc','si','wa','za');
$prevLabel = array();
$currLabelarr = array();
foreach( $arrunsort as $sortelem )
{
    $currLabel = substr($sortelem, 0, 1);
    if( $currLabel !== $prevLabel )
    {
        $currLabelarr[] = $currLabel;
        $prevLabel[] = $currLabel;
    }
}
echo "<pre>";
print_r($currLabelarr);

输出-

Array
(
    [0] => a
    [1] => a
    [2] => a
    [3] => c
    [4] => c
    [5] => s
    [6] => s
    [7] => w
    [8] => z
)

我预期的代码输出 -

Array
(
    [0] => a
    [1] => c
    [2] => s
    [3] => w
    [4] => z
)

我知道我可以使用array_unique()这个数组,但是我如何从上面的代码中管理它,因为 array_unique 的输出看起来不太好。

输出自print_r(array_unique($currLabelarr));

Array
(
    [0] => a
    [3] => c
    [5] => s
    [7] => w
    [8] => z
)
4

3 回答 3

2

Use array_values

print_r(array_values(array_unique($currLabelarr)));

Output

Array
(
[0] => a
[1] => c
[2] => s
[3] => w
[4] => z
)
于 2013-06-27T11:30:46.920 回答
0

Just Change --

$prevLabel[] = $currLabel;

To

$prevLabel = $currLabel;

output -

Array
(
    [0] => a
    [1] => c
    [2] => s
    [3] => w
    [4] => z
)
于 2013-06-27T11:30:35.200 回答
0

简单的

print_r(array_unique($currLabelarr));

您可以应用 array_values 打印基于值的唯一数组

print_r(array_values(array_unique($currLabelarr)));
于 2013-06-27T11:29:21.807 回答