3v4l.org

run code in 300+ PHP versions simultaneously
<?php function array_group_by($arr, $key) { if (!is_array($arr)) { trigger_error('array_group_by(): The first argument should be an array', E_USER_ERROR); } if (!is_string($key) && !is_int($key) && !is_float($key)) { trigger_error('array_group_by(): The key should be a string or an integer', E_USER_ERROR); } // Load the new array, splitting by the target key $grouped = []; foreach ($arr as $value) { $grouped[$value[$key]][] = $value; } // Recursively build a nested grouping if more parameters are supplied // Each grouped array value is grouped according to the next sequential key if (func_num_args() > 2) { $args = func_get_args(); foreach ($grouped as $key => $value) { $parms = array_merge([$value], array_slice($args, 2, func_num_args())); $grouped[$key] = call_user_func_array('array_group_by', $parms); } } return $grouped; } $rows = [ [ 'name' => 'This is apple', 'category' => 'apple', 'first_category' => 'fruit' ], [ 'name' => 'This is orange', 'category' => 'orange', 'first_category' => 'fruit' ], [ 'name' => 'This is pear', 'category' => 'pear', 'first_category' => 'fruit' ], [ 'name' => 'This is carrot', 'category' => 'carrot', 'first_category' => 'vegetable' ], [ 'name' => 'This is tomatoe', 'category' => 'tomatoe', 'first_category' => 'vegetable' ] ]; $items = array_group_by($rows, 'first_category'); var_dump($items);
Output for 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.5 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
array(2) { ["fruit"]=> array(3) { [0]=> array(3) { ["name"]=> string(13) "This is apple" ["category"]=> string(5) "apple" ["first_category"]=> string(5) "fruit" } [1]=> array(3) { ["name"]=> string(14) "This is orange" ["category"]=> string(6) "orange" ["first_category"]=> string(5) "fruit" } [2]=> array(3) { ["name"]=> string(12) "This is pear" ["category"]=> string(4) "pear" ["first_category"]=> string(5) "fruit" } } ["vegetable"]=> array(2) { [0]=> array(3) { ["name"]=> string(14) "This is carrot" ["category"]=> string(6) "carrot" ["first_category"]=> string(9) "vegetable" } [1]=> array(3) { ["name"]=> string(15) "This is tomatoe" ["category"]=> string(7) "tomatoe" ["first_category"]=> string(9) "vegetable" } } }

preferences:
141.98 ms | 411 KiB | 5 Q