示例输入为 json
{
"user":{
"name":"Thomas",
"age":101
},
"shoppingcart":{
"products":{
"p1":"someprod",
"p2":"someprod2"
},
"valuta":"eur",
"coupon":null,
"something":[
"bla1",
"bla2"
]
}
}
预期输出
[
'user.name' => 'Thomas',
'user.age' => 101,
'shoppingcart.products.p1' => 'someprod',
...
'shoppingcart.something.1' => 'bla1'
]
我已经编写了这个函数,但是它产生了错误的输出。接下来,我想将所述函数重写为 Collection
的宏,但我无法绕过它。问题还在于,当前函数需要一个全局变量来跟踪结果。
public function dotFlattenArray($array, $currentKeyArray = []) {
foreach ($array as $key => $value) {
$explodedKey = preg_split('/[^a-zA-Z]/', $key);
$currentKeyArray[] = end($explodedKey);
if (is_array($value)) {
$this->dotFlattenArray($value, $currentKeyArray);
} else {
$resultArray[implode('.', $currentKeyArray)] = $value;
array_pop($currentKeyArray);
}
}
$this->resultArray += $resultArray;
}
所以我的问题是双重的: 1. 有时函数没有给出正确的结果 2. 如何将这个递归函数重写为宏
Collection::macro('dotflatten', function () {
return ....
});
最佳答案
您尝试做的事情称为将多维数组转换为带点符号的数组。
你不需要重新发明轮子,Laravel 已经有了它的助手,叫做 array_dot() .
The array_dot function flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = array_dot($array);
// ['products.desk.price' => 100]
您只需要使用 json_decode()
将您的 json 转换为数组,然后使用 array_dot()
将其扁平化以获得带点符号的数组。
关于php - 如何将多维集合(数组)展平为宏(Laravel)中的点符号版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816325/