Geetika Geetika - 3 months ago 21
PHP Question

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

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

Answer

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

Comments