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

故事扮演 提交于 2020-03-28 07:02:07

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/31627029/how-to-split-array-into-groups-based-on-one-field-value-in-php-codeigniter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!