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