Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP group by similar value called by function

I have an element with title, type, description and so on. I have a DAO that defines all that and functions already created that extract the type for one element only: it’s getById().

How can I loop through all the elements and create groups of them by the same id?

$group = array();
foreach ($announcement as $announcements) {
    $announcementType = $this->getById($this->typeId());
}

I should put an "if" here, but I cannot understand how to "create a group for each elements with the same typeId".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s not clear why you cycle over $announcements, anyway you can try a solution like this:

$group = [];

foreach ($announcements as $announcement) {
   $id = $this->typeId();
   $group[$id][] = $this->getById($id);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading