How do I count occurrence of duplicate items in array

前端 未结 12 1308
我寻月下人不归
我寻月下人不归 2020-11-27 03:32

I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.

<
12条回答
  •  隐瞒了意图╮
    2020-11-27 04:35

    I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

    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);
    

提交回复
热议问题