欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2023-12-22 22:06:16
...
如以下代码:
    $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
            ]        
        ]
    ]

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

回复内容:

如以下代码:

    $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
            ]        
        ]
    ]

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

 [
            "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);

function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}
相关标签: php 数组

上一篇:

下一篇: