Category: Models & ORM

Q: Cakephp counting occurrence of duplicate values in find();

This is my code:

$ids = $this->Match->find('all', array('fields' => array('category_id'), 'conditions' => array('event_id' => $event_id, 'sort > ' => 0, 'finished' => 0, 'created' => $match_date), 'limit' => 10, 'order' => 'id DESC');
foreach ($ids as $id) {
  $ids[] = $id['Match']['category_id'];
}
//output
$ids = array(1031, 254, 543, 543, 1069, 799, 125, 983, 1105, 1106);

Is there a way to find and count occurrence of duplicate values via Cakephp's model?

SOLVED duplicate
2 Answers

Version: 2.4

user
Pidara

4

Accepted by Pidara

PHP's array_count_values() function:

$ids = array(1031, 254, 543, 543, 1069, 799, 125, 983, 1105, 1106);
$ids = array_count_values($ids);

//output
(
    [1031] => 1
    [254] => 1
    [543] => 2
    [1069] => 1
    [799] => 1
    [125] => 1
    [983] => 1
    [1105] => 1
    [1106] => 1
)

No, I think Cake does not provide such a method to handle duplicate values. You have to do it yourself.

$ids = $this->Match->find('all', array('fields' => array('category_id'), 'conditions' => array('event_id' => $event_id, 'sort > ' => 0, 'finished' => 0, 'created' => $match_date), 'limit' => 10, 'order' => 'id DESC');
$counting = array();
foreach ($ids as $id) {
  $counting[$id['Match']['category_id']]++;
}

//output $counting
Kristi
Kristi

137

Created: 27 Sep '16

Last Reply: 27 Sep '16

Replies: 2

Views: 488

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions