Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group array of php objects by object property

Tags:

php

I have a php object (book) with 3 properties: name, category, description I then have a list of these book objects in an array. I want to create a new associative array for these objects grouped by category.

Say I have 4 book objects in an array called $books

name    category  description
==================================
book1   cat1     this is book 1
book2   cat1     this is book 2
book3   cat2     this is book 3
book4   cat3     this is book 4

how can I create an associative array called $categories

$categories['cat1'] = array(book1, book2)
$categories['cat2'] = array(book2)
$categories['cat3'] = array(book3)

where book? is the book object and not the word

like image 621
John Avatar asked Mar 10 '11 18:03

John


2 Answers

Like this:

foreach($books as $book)
{ 
    $categories[$book->category][] = $book;
}
like image 128
Akarun Avatar answered Sep 24 '22 18:09

Akarun


Simply loop the array of objects into a new array with the key being the category:

$newArray = array();
foreach($array as $entity)
{
    if(!isset($newArray[$entity->category]))
    {
         $newArray[$entity->category] = array();
    }

    $newArray[$entity->category][] = $entity;
}

Is this what you was looking for ?

Explanation of the code:

/*
    * Create a new blank array, to store the organized data in.
*/
$newArray = array();

/*
    * Start looping your original dataset
*/
foreach($array as $entity)
{

    /*
        * If the key in the new array does not exists, set it to a blank array.
    */
    if(!isset($newArray[$entity->category]))
    {
         $newArray[$entity->category] = array();
    }

    /*
        * Add a new item to the array, making shore it falls into the correct category / key
    */
    $newArray[$entity->category][] = $entity;
}
like image 44
RobertPitt Avatar answered Sep 23 '22 18:09

RobertPitt