PHP如何高效地对根据键值对数组元素进行归类?

WBOY
Lepaskan: 2016-06-06 20:08:38
asal
1190 orang telah melayarinya

如以下代码:

<code>    $arr = [
        0 => [
            "category" => "red",
            "price" => 95
        ],
        1 => [
            "category" => "blue",
            "price" => 85
        ],    
        2 => [
            "category" => "red",
            "price" => 75
        ]
    ];
    
    //我希望将以上其归类为如下数组
    
    [
        "red" => [
            0 => [
                "category" => "red",
                "price" => 95
            ],            
            1 => [
                "category" => "red",
                "price" => 75
            ]        
        ],
        "blue" => [
            0 => [
                "category" => "blue",
                "price" => 85
            ]        
        ]
    ]</code>
Salin selepas log masuk
Salin selepas log masuk

希望大神能给个思路,谢谢

回复内容:

如以下代码:

<code>    $arr = [
        0 => [
            "category" => "red",
            "price" => 95
        ],
        1 => [
            "category" => "blue",
            "price" => 85
        ],    
        2 => [
            "category" => "red",
            "price" => 75
        ]
    ];
    
    //我希望将以上其归类为如下数组
    
    [
        "red" => [
            0 => [
                "category" => "red",
                "price" => 95
            ],            
            1 => [
                "category" => "red",
                "price" => 75
            ]        
        ],
        "blue" => [
            0 => [
                "category" => "blue",
                "price" => 85
            ]        
        ]
    ]</code>
Salin selepas log masuk
Salin selepas log masuk

希望大神能给个思路,谢谢

<code><?php $arr = [
        0 => [
            "category" => "red",
            "price" => 95
        ],
        1 => [
            "category" => "blue",
            "price" => 85
        ],    
        2 => [
            "category" => "red",
            "price" => 75
        ]
    ];

$result = array();
foreach($arr as $k=>$v){
    //var_dump($v);
    //echo $v['price'];
    $key = $v['category'];
    if(!array_key_exists($key, $result)) $result[$key] =array();
    $result[$key][] = $v;

}

var_dump($result);</code>
Salin selepas log masuk

<code>function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}</code>
Salin selepas log masuk
Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan