How to split array into groups based on one field value in PHP Codeigniter-ThrowExceptions

Exception or error:

I am having an array like this:

Array
(
[0] => stdClass Object
    (
        [vendor_id] => 11 
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Pre-Paid Airtime Recharge
    )

[1] => stdClass Object
    (
        [vendor_id] => 12 
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Pre-Paid Airtime Recharge
    )

[2] => stdClass Object
    (
        [vendor_id] => 13
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Bill Payments
    )
)
....

8 type of services are there and I want to group my data based on the service field’s value. Like this:

Service: Pre-Paid Airtime Recharge
[0] => stdClass Object
    (
        [vendor_id] => 13
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Pre-Paid Airtime Recharge
    )
[1] => stdClass Object
    (
        [vendor_id] => 14
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Pre-Paid Airtime Recharge
    )


Service: Bill Payments
[0] => stdClass Object
    (
        [vendor_id] => 15
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Bill Payments
    )
[1] => stdClass Object
    (
        [vendor_id] => 16
        [name] => Telkom Pin Airtime R100.00 
        [provider] => Telkom Mobile 
        [service] => Bill Payments
    )

Is it possible to do? pls guide

How to solve:

assume the original array’s name is $origin_data and after manipulation we put data that sorted by service name into $sorted_data

$sorted_data = array(); 
//its key value pair is like [service_name] => array( 0 => array(...),...)
foreach($origin_data as $item) {
    if(isset($sorted_data[$item[service]])) {
        $sorted_data[$item[service]][] = $item;
    }
}

Now each element of $sorted_data is a group of elements for one service

Answer´╝Ü

Use each iterated $item‘s service value as the parent/grouping key and push indexed elements into it.

$newarray = array();
foreach($array as $item) {
    $newarray[$item->service][] = $item;
}

print_r($newarray);

Demo on eval

Leave a Reply

Your email address will not be published. Required fields are marked *