skip to Main Content

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".

2

Answers


  1. 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);
    }
    
    Login or Signup to reply.
  2. You can also try with array_reduce (is not an common answer but still an answer):

    //Considering every announcement has an id
    
    
    $callback = function($prevResult, $item) { 
        $id = $item->typeId();
        $prevResult[$id][] = $this->getById($id);
        return $prevResult;
    };
    
    $groupedById = array_reduce($announcements, $callback, []);
    //empty array as last parameter if the announcements 
    //array is empty os the return type still the same
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search