多个数组值(某些值相同)如何仅获取两个值相同

时间:2019-05-23 09:25:49

标签: php

单个数组中有多个值(一些值相似) 怎么获得 其中之一是获取值相似的数组 最少重复1次,最多重复2次

例如此数组-

$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
foreach($array_value as $value){


}

我想要输出-ab,ab,cd,cd,de,xy

2 个答案:

答案 0 :(得分:0)

我认为您的输出shuold有两个 de 不是一个?

无论如何,这里是带有注释说明的代码:

<?php

$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');

$arr_count = []; //we use this array to keep track of how many times we've added this
$new_arr = []; //we add elements to this array, or not.

foreach($array_value as $value){
    // we've added it before
    if (isset($arr_count[$value])) {
        // we only add it again one more time, no more.
        if ($arr_count[$value] < 2) {
            $arr_count[$value]++;
            $new_arr[] = $value;
        }
    }
    // we haven't added this before
    else {
        $arr_count[$value] = 1;
        $new_arr[] = $value;
    }
}

sort($new_arr); 

print_r($new_arr); 
/*
(
    [0] => ab
    [1] => ab
    [2] => cd
    [3] => cd
    [4] => de
    [5] => de
    [6] => xy
) */

PHP Demo

答案 1 :(得分:0)

array_count_values返回数组中特定值的重复。因此,您可以使用它来简化代码并快速实现它。

$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
// Get count of every value in array
$array_count_values = array_count_values($array_value);
$result_array = array();
foreach ($array_count_values as $key => $value) {
    // Get $value as number of repetition of value and $key as value
    if($value > 2) {
        $value = 2;
        array_push($result_array, $key);
        array_push($result_array, $key);
    } else {
        for ($i=0; $i < $value; $i++) { 
            array_push($result_array, $key);
        }
    }
}
print_r($result_array);