如何从数组中获取唯一值

时间:2013-06-27 11:27:55

标签: php arrays sorting array-unique

当前代码 -

<?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
)

3 个答案:

答案 0 :(得分:2)

使用array_values

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

<强>输出

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

答案 1 :(得分:0)

简单

print_r(array_unique($currLabelarr));

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

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

答案 2 :(得分:0)

只需改变 -

$prevLabel[] = $currLabel;

$prevLabel = $currLabel;

输出 -

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