Walhalla Walhalla - 27 days ago 10
PHP Question

Convert Associative Array -> Grouping by Value

I have an associative array which looks like this:

enter image description here

I want to convert it.
It should be grouped by "product_service_category_name" and it should look like this:

$productServices = [
'' => [
1 => 'Diverses Service #1',
2 => 'Diverses Service #2'
],
'Beratung' => [
5 => 'Ernährungsberatung'
],
'Massagen' => [
3 => 'Heilmassage',
4 => 'Shiatsu'
]
];


Please take care about the fact, that the value maybe empty.

Could anybody help me with this?

Thank you!

Answer
function group($array)
{
    $group = array();
    $key = 'product_service_category_name';
    foreach (array_values($array) as $values) {

        if ( empty($values[$key])) {
            $ptr = 'empty';
        }
        else {
            $ptr = $values[$key];   
        }

        $new_key = $values['product_service_id'];
        $group[$ptr][$new_key] = $values['product_service_name'];   
    }
    return $group;
}

$grouped = group($ungrouped);

Test Here

Comments