CodeIgniter Forums

Full Version: Grouping and Sorting Arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[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] => toni.t@gmail.com [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] => nicolo.v@gmail.com [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] => john.smith@gmail.com [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!

El Forum

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

bam.

El Forum

[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...)
    )
)

*/

El Forum

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

That worked perfectly fine! Thanks!