How can PHP efficiently classify array elements based on key values?

Source: Internet
Author: User
As shown in the following code: {code...} hope the great God can give me a thought. Thank you for the following code:

$ Arr = [0 => ["category" => "red", "price" => 95], 1 => ["category" => "blue ", "price" => 85], 2 => ["category" => "red", "price" => 75]; // I want to classify the preceding data as the following array ["red" => [0 => ["category" => "red", "price" => 95], 1 => ["category" => "red", "price" => 75], "blue" => [0 => ["category" => "blue", "price" => 85]

Hope you can give me some ideas. Thank you.

Reply content:

Run the following code:

$ Arr = [0 => ["category" => "red", "price" => 95], 1 => ["category" => "blue ", "price" => 85], 2 => ["category" => "red", "price" => 75]; // I want to classify the preceding data as the following array ["red" => [0 => ["category" => "red", "price" => 95], 1 => ["category" => "red", "price" => 75], "blue" => [0 => ["category" => "blue", "price" => 85]

Hope you can give me some ideas. Thank you.


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.