【问题标题】:Recursive Array Map with Laravel Collection map() Helper带有 Laravel 集合 map() 帮助器的递归数组映射
【发布时间】:2016-04-20 14:17:58
【问题描述】:

我有一组数据。

$array = [

    [
        'id' => 1,
        'name' => 'some1',
        'type' => 'type1',
        'color' => 'color1',
        'quantity' => 1
    ],

    [
        'id' => 2,
        'name' => 'some1',
        'type' => 'type1',
        'color' => 'color1',
        'quantity' => 1
    ],

    [
        'id' => 3,
        'name' => 'some1',
        'type' => 'type1',
        'color' => 'color2',
        'quantity' => 1
    ],

    [
        'id' => 4,
        'name' => 'some2',
        'type' => 'color1',
        'color' => 'type1',
        'quantity' => 1
    ],

     ......
];

具有不同的名称、类型和颜色

我想按名称、类型和颜色对数据进行分组,结果是数组数据和同一组数据的汇总。

首先,我是这样用的:

function groupedData($array)
{

    $collection = [];

    collect($array)->groupBy('name')->map(

        function ($item) use (&$collection) { 

            return $item->groupBy('type')->map(

                function ($item) use (&$collection) { 

                    return $item->groupBy('color')->map(

                        function ($item) use (&$collection) {

                            $quantity = $item->sum('quantity');
                            $collection[] = collect($item[0])->merge(compact('quantity'));
                        }
                    );
                }
            ); 
        }
    );

    return $collection;
}

我希望输出应该是这样的:

$grouped = [

    [
        'id' => 1,
        'name' => 'some1',
        'type' => 'type1',
        'color' => 'color1',
        'quantity' => 2
    ],

    [
        'id' => 2,
        'name' => 'some1',
        'type' => 'type1',
        'color' => 'color2',
        'quantity' => 1
    ],

    [
        'id' => 3,
        'name' => 'some2',
        'type' => 'type1',
        'color' => 'color1',
        'quantity' => 2
    ],

    [
        'id' => 4,
        'name' => 'some2',
        'type' => 'type2',
        'color' => 'color1',
        'quantity' => 2
    ],
];

其中数量表示组项目的数量。

但是,我的问题是当需要更改时。以防万一 : 当用户想要添加其他类别进行分组时,例如: 用户可能希望按名称、类型、颜色和大小进行分组。

问题:如何做一个函数,让它更简单灵活,在require变化的时候不需要改代码?

感谢您的回答。

【问题讨论】:

  • 您的代码有两个return 语句,很难理解。你能展示一些示例输出数据吗?
  • 谢谢@JosephSilber 抱歉,我已经更新了问题。 :)

标签: php laravel collections


【解决方案1】:

您要查找的内容是排序,而不是分组。

这是一个简单的方法:

function sort($array, $keys) {
    return collect($array)->sortBy(function ($item) use ($keys) {
        return array_reduce($keys, function ($carry, $key) use ($item) {
            return $carry + $item[$key];
        }, '');
    })->all();
}

这里有一个简短的解释:

  1. 我们正在使用集合的 sortBy 方法,让我们使用一个回调函数,该函数将返回一个字符串来确定排序顺序。
  2. 我们在键上使用array_reduce 来构建一个包含我们要排序的键中所有值的字符串。
  3. Laravel 的集合对象将使用生成的字符串对集合进行排序。
  4. 最后,我们调用all方法从集合中获取底层数组。如果您想实际返回一个集合,可以删除最后一个 all 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2010-10-21
    • 2016-07-23
    相关资源
    最近更新 更多