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 = array(); 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(array($value), array_slice($args, 2, func_num_args())); $grouped[$key] = call_user_func_array('array_group_by', $parms); } } return $grouped; } $rows = array( array( 'name' => 'This is apple', 'category' => 'apple', 'first_category' => 'fruit' ), array( 'name' => 'This is orange', 'category' => 'orange', 'first_category' => 'fruit' ), array( 'name' => 'This is pear', 'category' => 'pear', 'first_category' => 'fruit' ), array( 'name' => 'This is carrot', 'category' => 'carrot', 'first_category' => 'vegetable' ), array( 'name' => 'This is tomatoe', 'category' => 'tomatoe', 'first_category' => 'vegetable' ) ); $items = array_group_by($rows, 'first_category'); foreach($items as $key => $value) { echo '<li><strong>' . $key . '</strong></li>'; foreach($value as $row) { echo '<li><a href="/category/'.$row['category'].'">'.$row['category'].'</a></li>'; } }

preferences:
30.17 ms | 405 KiB | 5 Q