从阵列中提取x个唯一值的次数

时间:2016-06-07 07:21:28

标签: php arrays

我有一个值数组(非唯一),我需要弄清楚我可以从该数组中提取多少次x(例如3)个唯一项。

e.g。

[5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5]

我可以检索的长度为3的唯一项目(例如[5, 4, 1])的最大数量是多少?

对于上下文,这适用于购物车中的优惠系统。值数组是产品ID,我需要知道有多少次我可以应用特定的商品需要3个不同的商品才能生效。

感谢您的帮助 - 只要询问是否有任何不清楚的地方,我会尝试解释。如果我错过了一个回答这个问题的现有问题,请告诉我,我会结束这个问题。

4 个答案:

答案 0 :(得分:0)

以下是您可以遵循的一种方式:

$basket = array(5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5);
$length = 3; //unique set size

function getSetCount($basket, $length) {
    $counts = array_count_values($basket); //count of each ID
    $totalCount = count($basket); //count of all elements

    //maximum amount of sets
    $max = floor($totalCount / $length);

    //since every ID can be only once in a set, it all above $max occurences won't be able to fit any set.
    $reducedCounts = array_map(function ($el) use ($max) {
        return min($el, $max);
    }, $counts);

    //final result is "all elements that should fit in sets / size of set
    return floor(array_sum($reducedCounts) / $length);
}

如果您想打印它们:

function printSets($basket, $length) {
    $counts = array_count_values($basket); //count of each ID

    while(!empty($counts)) {
        arsort($counts);//reverse sort with keeping the keys
        $set = array_slice(array_keys($counts),0,$length); //get the set
        echo implode(',', $set) . '<br/>';
        foreach($set as $id) { //reduce counts
            $counts[$id]--;
        }
        $counts = array_filter($counts); //clean zeros
    }
}

上面的代码可能无法处理一些边缘情况。但这就是这个想法。

基本上array_count_values()计算值&#39;出现并返回value => count对数组。然后很容易操纵这些数据。

答案 1 :(得分:0)

如果我理解正确的话:

function getChunksCount($products)
{   
    // get unique ids
    $uniqueProducts = array_unique($products);

    // count unique ids
    $count = count($uniqueProducts);

    // let's get the number of chucks available
    $chunkSize = 3;

    // round to the floor
    return floor($count / $chunkSize);
}

根本没有复杂的逻辑或处理。下次尝试写下究竟需要按什么顺序完成的内容,解决方案可能会变得非常明显:)

答案 2 :(得分:0)

您可以使用array_uniquearray_slice

来执行此操作
$arr = [5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5];

$new_arr = array_slice(array_unique($arr), 0, 3);
print_r($new_arr); //Array ( [0] => 5 [1] => 4 [2] => 1 )

答案 3 :(得分:0)

您可以使用array_count_values

<?php `$array = array(5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5); $vals = array_count_values($array); echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>'; print_r($vals);`?>

输出是-Array([5] =&gt; 4 [4] =&gt; 2 1 =&gt; 2 [2] =&gt; 2 [3] =&gt; 2)