erichert
erichert

Reputation: 150

Codeigniter Count rows with distinct values

What I am trying to do is to group rows of a table by distinct values and then count the results while also relating the counts to the distinct values.

so I have a table like this:

id | member.id | value1 | value2 | etc.

I need to count how many rows each member.id is associated with and return an array like below.

array(
  [member.id1] ['count'] => 'rowcount'
  [member.id2] ['count'] => 'rowcount'
   etc.
  )

I'm really stumped on how to do this using Codigniter's ActiveRecord and I don't want to run another db query in a foreach loop. Any help on what direction I should take would be most helpful.

Upvotes: 0

Views: 9219

Answers (1)

yAnTar
yAnTar

Reputation: 4610

Try so:

$items = $this->db->select('id, COUNT(id) AS count', false)
                  ->from('table')
                  ->group_by('member.id')
                  ->get()->result();

Output - array of objects with id user and count.

Upvotes: 8

Related Questions