当前代码 -
<?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
)
答案 0 :(得分:2)
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
)