【问题标题】:How to flatten a multidimensional collection (array) to a dot notation version in a macro (Laravel)?如何在宏(Laravel)中将多维集合(数组)展平为点符号版本?
【发布时间】:2018-09-23 18:34:25
【问题描述】:

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 ....

});

【问题讨论】:

标签: php arrays laravel recursion multidimensional-array


【解决方案1】:

您正在尝试做的事情是将多维数组转换为带有点符号的数组。

你不需要重新发明轮子,Laravel 已经为它提供了一个助手,叫做array_dot()

array_dot 函数将多维数组扁平化为 使用“点”表示深度的单级数组:

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

$flattened = array_dot($array);

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

您只需将您的 json 转换为带有 json_decode() 的数组,然后使用 array_dot() 将其展平即可获得带有点符号的数组。

【讨论】:

  • 有没有办法像 Collection flatten() 方法一样传递 depth 值?在我的用例中,我的多维数组是一个恒定的深度,但我需要展平到倒数第二个级别
猜你喜欢
  • 1970-01-01
  • 2018-07-22
  • 2020-09-13
  • 1970-01-01
  • 2019-07-05
  • 2015-12-31
  • 1970-01-01
  • 2018-02-03
  • 2020-05-07
相关资源
最近更新 更多