programing

배열에서 중복 항목의 발생을 계산하는 방법

javajsp 2023. 8. 2. 08:47

배열에서 중복 항목의 발생을 계산하는 방법

배열에 있는 각 중복 항목의 발생 횟수를 세어 각각의 발생 횟수를 고유/비중복 항목의 배열로 만들고자 합니다.

여기 제 코드가 있습니다. 하지만 어디서 잘못되고 있는지 모르겠습니다!

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

//$previous[value][Occurrence]

for($arr = 0; $arr < count($array); $arr++){

    $current = $array[$arr];
    for($n = 0; $n < count($previous); $n++){
        if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
            if($current != $previous[count($previous)][0]){
                $previous[$n++][0] = $current;
                $previous[$n++][1] = $counter++;
            }
        }else{  
            $previous[$n][1] = $counter++;
            unset($previous[count($previous)-1][0]);
            unset($previous[count($previous)-1][1]);
        }   
    }
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>    

array_count_values즐기세요 :-)

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);

결과:

No. of NON Duplicate Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)

없이 시도하고 싶다면,'array_count_values'당신은 여기서 현명한 방법으로 할 수 있습니다.

<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

$count_values = array();
foreach ($input as $a) {

     @$count_values[$a]++;

}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>

가장 간단한 솔루션(PHP가 작동하는 부분) - 중복만:

$r = array_filter(array_count_values($array), function($v) { return $v > 1; });

및 확인:

print_r($r);

결과$r:

[43] => 6
[21] => 2
[78] => 2

PHP 5.5+에서 사용할 수 있는 다차원 배열이 있다면 다음과 같습니다.

array_count_values(array_column($array, 'key'))

이는 예를 들어 반환합니다.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

저는 최근에 이런 상황에서 도움이 될 배열 내의 하위 문자열을 확인하는 기능을 만들었습니다.

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);

텍스트 항목 배열과 함께 사용할 수도 있습니다. 중복되는 수를 제대로 얻을 수 있지만 PHP는 표시합니다.

경고: array_count_values(): STRING 및 INTERGER 값만 카운트할 수 있습니다!

$domains = 
array (
  0 => 'i1.wp.com',
  1 => 'i1.wp.com',
  2 => 'i2.wp.com',
  3 => 'i0.wp.com',
  4 => 'i2.wp.com',
  5 => 'i2.wp.com',
  6 => 'i0.wp.com',
  7 => 'i2.wp.com',
  8 => 'i0.wp.com',
  9 => 'i0.wp.com' );

$tmp = array_count_values($domains);
print_r ($tmp);

    array (
      'i1.wp.com' => 2730,
      'i2.wp.com' => 2861,
      'i0.wp.com' => 2807
    )

내장 함수를 사용하지 않고 PHP에서 배열의 중복 요소를 카운트

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

PHP가 제공하는 in_array()라는 마법의 기능이 있습니다.

코드의 일부를 사용하여 루프를 다음과 같이 수정합니다.

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    }
    else{
        $arr2[] = $array[$arr];
    }
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>

위의 코드 스니펫은 반복되는 총 항목 수를 반환합니다. 즉, 샘플 배열 43이 5회 반복되고 78이 1회 반복되고 21이 1회 반복되면 반복되지 않고 배열을 반환합니다.

각 루프에 대해 를 사용하여 수행할 수 있습니다. (데모)

$array = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
    $set_array[$value]++;
}
print_r($set_array);     

출력:

Warning: Undefined array key 1 in /in/aGPqe on line 6

Warning: Undefined array key 2 in /in/aGPqe on line 6

Warning: Undefined array key 3 in /in/aGPqe on line 6

Warning: Undefined array key 4 in /in/aGPqe on line 6

Warning: Undefined array key 5 in /in/aGPqe on line 6

Warning: Undefined array key 6 in /in/aGPqe on line 6

Warning: Undefined array key 88 in /in/aGPqe on line 6
Array
(
    [1] => 3
    [2] => 3
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 2
    [88] => 1
)

저는 구글에서 배열에서 중복 항목의 발생을 셀 수 있는 방법을 찾아 왔습니다.간단히 수행할 수 있는 방법은 다음과 같습니다.

$colors = ["red", "green", "blue", "red", "yellow", "blue"];

$unique_colors = array_unique($colors);                // ["red", "green", "blue", "yellow"]
$duplicates = count($colors) - count($unique_colors);  // 6 - 4 = 2

if ($duplicates == 0) {
    echo "There are no duplicates";
}
echo "No. of Duplicates: " . $duplicates;

// Output: No. of Duplicates are: 2

array_unique()는 어떻게 작동합니까?

모든 중복 요소를 포함합니다.ex: 다음과 같은 배열이 있다고 가정합니다.

$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");

할 때$cars = array_unique($cars);자동차는 오직 다음과 같은 요소들만 가질 것입니다.$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

자세한 내용은 https://www.php.net/manual/en/function.array-unique.php 을 참조하십시오.

이 코드는 동일한 배열에 중복 값을 반환합니다.

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
    $input = [1,2,1,3,2,4,10];
    //if give string
    //$input = "hello hello how are you how hello";
    //$array = explode(' ',$input);
    $count_val = [];
    foreach($array as $val){
      $count_val[$val]++;
    }
    print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )

언급URL : https://stackoverflow.com/questions/13633954/how-do-i-count-occurrence-of-duplicate-items-in-array