phparraysassociative-arraymerging-dataarray-flip

Flip associative array and store new values in subarrays to prevent losing duplicated values


I have a flat associative array which may contain duplicate values.

Array (
    [for-juniors] => product_category 
    [for-men] => product_category
    [coats] => product_category
    [for-women] => product_category
    [7-diamonds] => brand
) 

I need to restructure the data to store the original values as new keys and the original keys pushed into subarrays associated with the new keys.

array(
    'product_category' => array(
        'for-juniors',
        'for-men',
        'coats',
        'for-women'
    ),
    'brand' => array(
        '7-diamonds'
    )
);

Solution

  • $grouped = array();
    foreach ($input as $choice => $group) {
        $grouped[$group][] = $choice;
    }
    
    var_dump($grouped);