计算我的数组中有多少重复和唯一值

时间:2016-04-19 08:43:06

标签: php arrays

我有一个这样的数组:

array (size=6)
0 => 
     array (size=1)

     'test' => string 'AQHRmVBW7uTgObjnzkqrp' (length=30)  

1 =>  array (size=1)
     'test' => string 'AQHRmU8HooJPnCKUfkGLD' (length=30)   
2 => 
     array (size=1)

     'test' => string 'AQHRmU7+BdwM7pmpzEKew' (length=30)   
3 => 
     array (size=1)
     'test' => string 'AQHRmU74sTU6YP4GsEee8' (length=30)   
4 => 
     array (size=1)
     'test' => string 'AQHRmOqQAoHUgxj7T0et8' (length=30)   
5 => 
     array (size=1)
     'test' => string 'AQHRmOqQAoHUgxj7T0et8' (length=30)

现在我想计算一下我的数组中有多少偶数值以及我有多少不均匀值。

正如您所看到的,最后两个结果在数组中是相同的,而其他4个结果都是唯一的。所以我希望我的最终结果是:

even: 2
uneven: 4

3 个答案:

答案 0 :(得分:1)

这是我们的阵列:

public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    myData = myArrayList.get(i);
//OR
    myData = myAdapter.getItem(i);
}

现在让它有一些fn:

$testArr = array(
    array('test' => 'AQHRmVBW7uTgObjnzkqrp'),
    array('test' => 'AQHRmU8HooJPnCKUfkGLD'),
    array('test' => 'AQHRmU7+BdwM7pmpzEKew'),
    array('test' => 'AQHRmU74sTU6YP4GsEee8'),
    array('test' => 'AQHRmOqQAoHUgxj7T0et8'),
    array('test' => 'AQHRmOqQAoHUgxj7T0et8'),
);

让我们看看我们有什么:

//First, let's flatten it
$flattenArr = array_column($testArr, 'test');
//And let's count values
$valsArr = array_count_values($flattenArr);

//Now filter elements that have only one occurrence
$unevenArr = array_filter($valsArr, function($val) {
    return $val==1;
});

//So now we can simply count this array to get "uneven" count...
$uneven = count($unevenArr);
//...and the rest is even
$even = count($testArr) - $uneven;

答案 1 :(得分:0)

$results = array();
foreach($array as $key => $value)
{
     if(!isset($results[$value['test']])) $results[$value['test']]=0;
     $results[$value['test']]++;
}

//count even and uneven
$uneven = 0;
$even = 0;
foreach($results as $key => $count)
{
    if($count>1) $even += $count;
    else $uneven++;
}

echo 'Even: '.$even.'<br>';
echo 'Uneven: '.$uneven.'<br>';

答案 2 :(得分:-1)

首先,您需要通过使用array_merge()将每个subArray作为参数调用call_user_func_array()来将数组展平为一维数组。想象一下:

$flatten = array_merge($subArrayOne, $subArrayTwo /* , ... */);

然后,您可以使用array_count_values()计算数组中的所有值,循环遍历该数组并创建预期的输出。

代码

<?php

    $arr = call_user_func_array("array_merge", $arr);
    $result = ["duplicates" => 0, "unique" => 0];

    foreach(array_count_values($arr) as $v => $count){
        if($count == 1)
            $result["unique"] += $count;
        else
            $result["duplicates"] += $count;
    }

    print_r($result);

?>

输出

Array
(
    [duplicates] => 4
    [unique] => 3
)