PHP有array_count_values的问题

时间:2011-04-12 12:14:06

标签: php arrays

我需要在我的数组上出现一次,我的代码只得到第一个结果,这是我的示例代码:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

提前致谢

ciao h

5 个答案:

答案 0 :(得分:2)

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        echo $arr[$i];
    }
}

应显示bcd

答案 1 :(得分:1)

可能你错过了真实的结果:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
/*
now $arrs is:
array (
  'a' => 2,
  'b' => 1,
  'c' => 1,
  'd' => 1,
)
*/

foreach($arrs as $id => $count){
 if($count==1) {
   // do your code
 }
}

/*******************************************************/
/* usefull version                                     */
/*******************************************************/

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);


foreach($arr as $id ){
 if($arrs[$id]==1){ 
   // do your code
   echo "$id is single\n";
 }
}

答案 2 :(得分:1)

$arr=array("a","a","b","c","d");
$result = array();
$doubles = array();
while( !empty( $arr ) ) {
    $value = array_pop( $arr );
    if( !in_array( $value, $arr ) 
            && !in_array( $value, $doubles ) ) {
        $result[] = $value;
    }
    else {
        $doubles[] = $value;
    }
}

答案 3 :(得分:0)

你只需要检索在数组中只出现一次的任何值,对吧?试试这个:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);

foreach ($arrs as $uniqueValue => $count)
{
  if($value == 1) {
    echo $uniqueValue; 
  }
}

array_count_values返回一个关联数组,其中键是找到的值,其值是它在原始数组中出现的次数。这个循环简单地迭代在你的数组中找到的每个唯一值(即来自array_count_values的键)并检查它是否只被发现一次(即该键的值为1)。如果是,则echo输出值。当然,您可能希望对该值执行更复杂的操作,但这可以作为占位符。

答案 4 :(得分:-1)

$count = 0;
foreach(array("a","a","b","c","d") as $v){
    if($v == 1){$count++;}
}