递归函数生成FQDN异常求助:多维数组键拼接展开需求
解决多维数组按点路径扁平化的递归问题
我来帮你搞定这个多维数组扁平化的问题!你想要把嵌套数组转换成$key.$subkey1.$subkey2...$subkeyN = $value的格式,但递归函数没生成正确的完整路径(FQDN)对吧?先结合你的测试用例,我来分析可能的问题点,再给出能达到预期结果的实现。
可能的递归错误点
通常这类问题出在前缀键的传递和拼接上:
- 递归调用时没有把当前层级的键作为前缀传递给子数组处理
- 前缀拼接时没处理根级(无前缀)的情况,导致键前面多出多余的点
- 递归返回的结果没有正确合并到主结果数组中,而是被覆盖
正确的递归实现代码
下面是一个能正确生成点分隔路径的递归函数,完全适配你的测试用例:
/** * 将多维数组扁平化为点分隔键的键值对数组 * @param array $array 要处理的输入数组 * @param string $prefix 父级键的前缀(递归时自动传递) * @return array 扁平化后的数组 */ function flattenArray($array, $prefix = '') { $result = []; foreach ($array as $key => $value) { // 构建当前键的完整路径:无前缀时直接用当前键,有前缀时拼接点 $currentFullKey = $prefix ? "{$prefix}.{$key}" : $key; if (is_array($value)) { // 递归处理子数组,把当前完整路径作为前缀传递 $result = array_merge($result, flattenArray($value, $currentFullKey)); } else { // 非数组值直接存入结果数组 $result[$currentFullKey] = $value; } } return $result; }
在你的测试函数中使用
把这个函数集成到你的测试代码里,就能得到符合预期的结果:
public function testBuildReverseSchemaNames() { $input = [ 'propertyZeroSchema' => 'value_0', 'communicationPreferences' => [ 'grv3_newsletter_bi' => true ], 'someContainer' => [ 'propertyOneSchema' => 'value_1' ], 'propertyThreeSchema' => 'value_3' ]; $expected = [ 'propertyZeroSchema' => 'value_0', 'communicationPreferences.grv3_newsletter_bi' => true, 'someContainer.propertyOneSchema' => 'value_1', 'propertyThreeSchema' => 'value_3' ]; // 调用扁平化函数 $actual = flattenArray($input); // 验证结果是否符合预期 $this->assertEquals($expected, $actual); }
额外测试:更深层级的嵌套
这个函数也支持更深的嵌套结构,比如:
$deepInput = [ 'level1' => [ 'level2' => [ 'level3' => 'deep_value' ] ] ]; // 输出:['level1.level2.level3' => 'deep_value']
内容的提问来源于stack exchange,提问作者JorgeeFG
相关产品推荐
相关产品推荐

