PHP中如何拆分数组?按资源后缀分组路由数组的需求
按资源后缀分组数组的实现方案
嘿,这需求太常见啦,咱们用PHP就能轻松搞定这个分组需求,下面给你两种实用的写法,按需选就行:
方法一:用array_reduce简洁实现
这种写法用数组内置函数,代码更紧凑利落:
$array = [ "index-category", "create-category", "store-category", "show-category", "index-products", "create-products", "store-products", "show-products", "edit-products", "index-sales", "create-sales" ]; $grouped = array_reduce($array, function($carry, $item) { // 拆分元素,提取后缀部分 $parts = explode('-', $item); $suffix = end($parts); // 对应分组不存在的话先初始化 if (!isset($carry[$suffix])) { $carry[$suffix] = []; } // 把当前元素塞进对应分组 $carry[$suffix][] = $item; return $carry; }, []); // 转为数字索引数组(和你示例结构完全匹配) $grouped = array_values($grouped); print_r($grouped);
方法二:用foreach循环(新手友好,逻辑一目了然)
要是觉得函数式写法有点绕,普通循环的逻辑会更直观:
$array = [ "index-category", "create-category", "store-category", "show-category", "index-products", "create-products", "store-products", "show-products", "edit-products", "index-sales", "create-sales" ]; $grouped = []; foreach ($array as $item) { $parts = explode('-', $item); $suffix = end($parts); // 检查分组是否存在,不存在就新建 if (!isset($grouped[$suffix])) { $grouped[$suffix] = []; } $grouped[$suffix][] = $item; } // 转为数字索引数组 $grouped = array_values($grouped); print_r($grouped);
最终输出效果
运行上面任意一段代码,都会得到和你需求一致的多维数组:
Array ( [0] => Array ( [0] => index-category [1] => create-category [2] => store-category [3] => show-category ) [1] => Array ( [0] => index-products [1] => create-products [2] => store-products [3] => show-products [4] => edit-products ) [2] => Array ( [0] => index-sales [1] => create-sales ) )
核心逻辑其实就是拆分每个元素拿到后缀,把相同后缀的元素归为一组,两种方法本质逻辑一样,选你看着顺手的用就好~
内容的提问来源于stack exchange,提问作者Wreigh
相关产品推荐
相关产品推荐

