求助:递归移除数组键前缀功能实现问题
解决嵌套数组键名去父前缀的递归实现
我明白你要解决的问题——把嵌套数组里每个带父键前缀的子键,去掉重复的前缀部分,对吧?递归确实是处理这种多层嵌套结构的最优方案,我来帮你写一个能完美实现需求的递归函数。
核心思路
咱们拆解一下逻辑:
- 遍历数组的每个键值对
- 如果当前值是子数组,就递归处理这个子数组,同时把当前键(加上下划线)作为新的前缀传递给递归调用
- 如果当前值是普通元素,就把键名里的父前缀替换为空,得到干净的新键名
实现代码
function removeParentPrefix(array $array, string $parentPrefix = ''): array { $result = []; foreach ($array as $key => $value) { // 处理子数组:递归调用,传递当前键作为新的前缀(加下划线匹配格式) if (is_array($value)) { $result[$key] = removeParentPrefix($value, $key . '_'); } else { // 去掉键名中的父前缀,生成新键 $newKey = str_replace($parentPrefix, '', $key); $result[$newKey] = $value; } } return $result; } // 测试你的输入数组 $input = array( 'seo_text' => array( 'seo_text_title' => '', 'seo_text_description' => '', 'seo_text_button' => array( 'seo_text_button_text' => '', 'seo_text_button_url' => '', 'seo_text_button_new_tab_enabled' => '', ), ), ); // 转换并输出结果 $output = removeParentPrefix($input); print_r($output);
效果验证
运行这段代码后,你会得到完全符合预期的输出:
Array ( [seo_text] => Array ( [title] => [description] => [button] => Array ( [text] => [url] => [new_tab_enabled] => ) ) )
这个函数的优势在于它能灵活处理任意深度的嵌套数组,只要你的键名格式是父键_子键这种规则,都能正确去除前缀。
内容的提问来源于stack exchange,提问作者Rahul Verma
相关产品推荐
相关产品推荐

