CodeIgniter Forums
Grouping and Sorting Arrays - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter Archived (from EllisLab) (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Grouping and Sorting Arrays (/showthread.php?tid=21517)



Grouping and Sorting Arrays - El Forum - 08-12-2009

[eluser]phused[/eluser]
I'm having problems grouping arrays based on the value of an item within an array.

I have the following array:

Array (
[0] => stdClass Object ( [company_id] => 1 [company_name] => My Company [user_id] => 4 [user_email] => [email protected] [user_username] => toni [meta_name] => Toni [meta_surname] => Trivkovic [meta_company_id] => 1 )

[1] => stdClass Object ( [company_id] => 2 [company_name] => Ignited Labs [user_id] => 5 [user_email] => [email protected] [user_username] => nick [meta_name] => Nicolo [meta_surname] => Volpato [meta_company_id] => 2 )

[2] => stdClass Object ( [company_id] => 2 [company_name] => Ignited Labs [user_id] => 6 [user_email] => [email protected] [user_username] => john [meta_name] => John [meta_surname] => Smith [meta_company_id] => 2 )
)

What I would like to do is reconstruct this array so users under the same company are grouped within a company's array. In this example nick and john would be grouped under one array (My Company) and toni would be grouped in another.

I'm aware I would probably have to use the array_push() function within a loop but I'm having issues getting this code working. Does anyone have any samples of code or resources they can link me to which shows users how to work with something like this?

Thanks!


Grouping and Sorting Arrays - El Forum - 08-12-2009

[eluser]richthegeek[/eluser]
Code:
$companies = array();
foreach( $people as $person ) $companies[ $person->company_id ][] = $person;

bam.


Grouping and Sorting Arrays - El Forum - 08-12-2009

[eluser]Nick Husher[/eluser]
Would something like the following not work?

Code:
$items = //your array
$sorted = array(); //the output

foreach($items as $item) {
    $company_id = $item->company_id;
    
    if(!isset($sorted[$company_id])) {
        $sorted[$company_id] = array();
    }
    $sorted[$company_id][] = $item;
}

/* result should be

Array (
    [1] => Array (
        [0] => stdClass Object ( ...[meta_name] => Toni...)
    )
    [2] => Array (
        [0] => stdClass Object ( ...[meta_name] => Nicolo...)
        [1] => stdClass Object ( ...[meta_name] => John...)
    )
)

*/



Grouping and Sorting Arrays - El Forum - 08-12-2009

[eluser]phused[/eluser]
[quote author="Nick Husher" date="1250104268"]Would something like the following not work?
[/quote]

That worked perfectly fine! Thanks!