如何在宏(Laravel)中将多维集合(数组)展平为点符号版本?

onl*_*mas 3 php arrays recursion multidimensional-array laravel

输入为json的示例

{
   "user":{
      "name":"Thomas",
      "age":101
   },
   "shoppingcart":{
      "products":{
         "p1":"someprod",
         "p2":"someprod2"
      },
      "valuta":"eur",
      "coupon":null,
      "something":[
         "bla1",
         "bla2"
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

预期产出

[
    'user.name' => 'Thomas',
    'user.age' => 101,
    'shoppingcart.products.p1' => 'someprod',
    ...
    'shoppingcart.something.1' => 'bla1'
]
Run Code Online (Sandbox Code Playgroud)

我写了这个函数,但它产生了错误的输出.接下来,我想将所述函数重写为宏,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;
    }
Run Code Online (Sandbox Code Playgroud)

所以我的问题是双重的:1.有时函数没有给出正确的结果2.如何将这个递归函数重写为宏

Collection::macro('dotflatten', function () {
    return ....

});
Run Code Online (Sandbox Code Playgroud)

Tro*_*yer 7

您要做的事情是将多维数组转换为带点符号的数组.

你不需要重新发明轮子,Laravel已经有了一个帮助器,称为array_dot().

所述array_dot函数变平的多维阵列到使用"点"符号来指示深度的单个水平阵列:

$ array = ['products'=> ['desk'=> ['price'=> 100]]];

$ flattened = array_dot($ array);

// ['products.desk.price'=> 100]

您只需要将json转换为数组,json_decode()然后将其平展array_dot()以获得带点符号的数组.