在Laravel中将多维集合(数组)转换为带点分隔键的扁平化结构
嘿,刚好之前处理过一模一样的需求,在Laravel里把多维集合/数组转成带点分隔键的扁平化结构其实超简单,我给你分享两种实用方法:
方法一:直接用Laravel集合的内置
dot()方法 这是最省心的方案,Laravel的Collection类已经内置了专门的dot()方法,完全匹配你的需求——它会自动把多维集合/数组转换成键为点分隔的扁平化结构,连数组的数字索引都会转换成点后缀,完美符合你给出的预期输出。
举个实际使用的例子,就用你提供的输入JSON:
// 先把JSON字符串转成数组,再转成Laravel集合 $inputJson = '{"user":{"name":"Thomas","age":101},"shoppingcart":{"products":{"p1":"someprod","p2":"someprod2"},"valuta":"eur","coupon":null,"something":["bla1","bla2"]}}'; $originalData = json_decode($inputJson, true); $collection = collect($originalData); // 调用dot方法完成扁平化 $flattenedData = $collection->dot(); // 最终输出的结构就是你要的: // [ // 'user.name' => 'Thomas', // 'user.age' => 101, // 'shoppingcart.products.p1' => 'someprod', // 'shoppingcart.products.p2' => 'someprod2', // 'shoppingcart.valuta' => 'eur', // 'shoppingcart.coupon' => null, // 'shoppingcart.something.0' => 'bla1', // 'shoppingcart.something.1' => 'bla2', // ]
小提示:如果你的原始数据本身就是Laravel集合(比如Eloquent查询返回的集合),直接调用->dot()就行,不用额外转数组再转集合~
方法二:自定义递归函数(适合需要定制逻辑的场景)
如果内置方法满足不了你的特殊需求(比如要过滤掉null值、自定义键的分隔符),可以自己写一个递归函数来灵活处理:
/** * 把多维数组/集合转成带点分隔键的扁平化结构 * @param array $array 要处理的多维数组 * @param string $prefix 键的前缀,递归时自动传递 * @return array 扁平化后的数组 */ function flattenWithDotKeys($array, $prefix = '') { $result = []; foreach ($array as $key => $value) { // 拼接当前层级的键 $currentKey = $prefix ? "{$prefix}.{$key}" : $key; // 如果当前值是 non-empty 数组,递归处理 if (is_array($value) && !empty($value)) { $result = array_merge($result, flattenWithDotKeys($value, $currentKey)); } else { // 这里可以加自定义逻辑,比如过滤null值:if ($value !== null) $result[$currentKey] = $value; } } return $result; } // 使用示例: $inputJson = '{"user":{"name":"Thomas","age":101},"shoppingcart":{"products":{"p1":"someprod","p2":"someprod2"},"valuta":"eur","coupon":null,"something":["bla1","bla2"]}}'; $originalData = json_decode($inputJson, true); $flattenedData = flattenWithDotKeys($originalData);
比如你想跳过null值,只需要在else分支里加个判断:if ($value !== null) $result[$currentKey] = $value; 就行,非常灵活。
内容的提问来源于stack exchange,提问作者online Thomas
相关产品推荐
相关产品推荐

