翻转关联数组并将新值存储在子数组中以防止丢失重复值 [英] Flip associative array and store new values in subarrays to prevent losing duplicated values

查看:32
本文介绍了翻转关联数组并将新值存储在子数组中以防止丢失重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能包含重复值的平面关联数组.

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'
    )
);

推荐答案

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

var_dump($grouped);

这篇关于翻转关联数组并将新值存储在子数组中以防止丢失重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆