user4559334
user4559334

Reputation: 373

Count each repeated value mysql result array

I would like to count all the repeated values in a mysql result array. For example

array (
[0] = > array (
 ["id"] => 1
["n"] => "ab"
)
[1] = > array (
 ["id"] => 5
["n"] => "bc"
)
[2] = > array (
 ["id"] => 4
["n"] => "cd"
)
[3] = > array (
 ["id"] => 1
["n"] => "ef"
)
)

So, taking the multidemensional array above, I want to count the amount of times each value of id is repeated in the array.

The result would be

1 = 2 times
5 = 1 time
4 = 1 time

I know I can do this with the array_search() function, but in my case, I don't know what i'm searching for. I just need the amount of results that have a specific repeated value.

Upvotes: 1

Views: 82

Answers (2)

potashin
potashin

Reputation: 44581

You can try the following, using foreach loop:

$final = array();
foreach($array as $ar)
    $final[$ar["id"]] = isset($final[$ar["id"]]) ? $final[$ar["id"]] + 1 : 1; 

Output:

array(3) {
  [1]=>
  int(2)
  [5]=>
  int(1)
  [4]=>
  int(1)
}

Demonstration

Upvotes: 1

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

You can use array_count_values()

$array = array ( 0 => array("id" => 1, "n" => "ab"), 1 => array("id" => 5, "n" => "bc"), 2 => array("id" => 4, "n" => "cd"), 3 => array("id" => 1, "n" => "ef"));
$counts = array_count_values(array_column($array, "id"));
print_r($counts);

Upvotes: 1

Related Questions