Passionate Engineer
Passionate Engineer

Reputation: 10412

Find out total count of duplicate value in result array Codeigniter

I'm trying to find count of duplicate values in result received from active record in codeigniter.

For example:

1 => 12
2 => 21
3 => 22
4 => 21
5 => 12
6 => 45

Is there a way we can find out total count so it comes out with 12 = 1, 21 = 2, 22 =1, 12 = 2, 45 = 1 etc?

Codeigniter way would be great but I am also open to PHP way.

OK array_count_values does not work with below array:

Array
(
    [0] => Array
        (
            [key_id] => 1790
            [key_name] => printer brisbane
            [link_id] => 1130
            [link_url] => 99cards.com
        )

    [1] => Array
        (
            [key_id] => 1982
            [key_name] => test
            [link_id] => 1130
            [link_url] => 99cards.com
        )

)

Is there a way we can find out that link_id count is 2?

I found answer myself. Below is the code:

$e = 0;
            foreach ($q as $qs){
                $i = 1;
                foreach ($q as $qss){
                    if($qss['link_id'] == $qs['link_id']){
                        $q[$e]['link_count'] = $i;
                    }
                    $i++;
                }
                $e++;
            }

Upvotes: 0

Views: 2334

Answers (2)

Vikk
Vikk

Reputation: 3363

We can do it manually as follows:

$count_array = array();
foreach($results as $result)
{
    $link_id = $result['link_id'];
    if(isset($count_array[$link_id]))
    {
        $count_array[$link_id] = $count_array[$link_id]+1;
    }
    else
    {
        $count_array[$link_id] = 1;
    }
}

Upvotes: 0

xkeshav
xkeshav

Reputation: 54050

array_count_values() made for such purpose

it Returns an associative array of values from input as keys and their count as value.

$array = array(1, "hello", 1, "world", "hello"); 
print_r(array_count_values($array)); 

The above example will output:

Array (
    [1] => 2
    [hello] => 2
    [world] => 1 )

Upvotes: 3

Related Questions