1

我有一个关于数组的问题。

我已经制作了一个ID数组。

数组看起来有点像这样。

$iIds[0] = 12  
$iIds[1] = 24  
$iIds[2] = 25  
$iIds[3] = 25  
$iIds[4] = 25  
$iIds[5] = 30

现在我需要代码来查看数组中是否有任何值多次。然后,如果该值在数组中出现 3 次,则将该值注入另一个数组。

我尝试使用 array_count_values() ,但它以值作为键返回。

谁能帮我这个?

4

3 回答 3

2
$iIds[0] = 12  
$iIds[1] = 24  
$iIds[2] = 25  
$iIds[3] = 25  
$iIds[4] = 25  
$iIds[5] = 30
$counts = array_count_values($iIds);
$present_3_times = array();
foreach($counts as $v=>$count){
    if($count==3)//Present 3 times
        $present_3_times[] = $v;
}
于 2012-10-31T10:38:42.510 回答
2
  1. 计数值
  2. 过滤器阵列
  3. 将数组翻转回你想要的样子

    $cnt = array_count_values($iIds);

    $filtered = array_filter($cnt, create_function('$x', 'return $x == 3;'));

    $final = array_flip($filtered);

或者

array_flip(array_filter( array_count_values($iIds), create_function('$x', 'return $x == 3;')));

见:http ://codepad.org/WLaCs5Pe

编辑

如果最终数组中可能有多个值,我建议不要翻转过滤后的数组,只需使用 array_keys,这样它就会变成:

$cnt = array_count_values($iIds);

$filtered = array_filter( $cnt, create_function('$x', 'return $x == 3;'));

$final = array_keys($filtered);

见:http ://codepad.org/ythVcvZM

于 2012-10-31T10:48:27.137 回答
1

要创建唯一的数组,请使用array_uniquephp 函数,然后要重新排列数组的键,请使用array_valuesphp 函数,如下所示。

$iIds[0] = 12 ;
$iIds[1] = 24 ; 
$iIds[2] = 25 ;
$iIds[3] = 25 ; 
$iIds[4] = 25 ;
$iIds[5] = 30 ;


$unique_arr = array_unique($iIds);
$unique_array  = array_values($unique_arr);

print_r($unique_array);

为了获得一个值数组,在数组中作为重复值出现了 3 次

$iIds[0] = 12 ; 
$iIds[1] = 24 ;
$iIds[2] = 25 ;
$iIds[3] = 25 ;
$iIds[4] = 25 ;
$iIds[5] = 30 ;

$arr =  array_count_values($iIds);

$now_arr = array();
foreach($arr AS $val=>$count){
   if($count == 3){
      $now_arr[] = $val; 
   }
 }
 print_r($now_arr);

谢谢

于 2012-10-31T10:51:50.480 回答