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'); 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>'; } }
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.30, 7.0.0 - 7.0.25, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 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
<li><strong>fruit</strong></li><li><a href="/category/apple">apple</a></li><li><a href="/category/orange">orange</a></li><li><a href="/category/pear">pear</a></li><li><strong>vegetable</strong></li><li><a href="/category/carrot">carrot</a></li><li><a href="/category/tomatoe">tomatoe</a></li>

preferences:
113.8 ms | 409 KiB | 5 Q