按列对二维数组的行进行分组,并将每组中的另一列连接为逗号分隔的字符串

问题描述 投票:0回答:2

我有这样的数组:

[
   0: {name: "Judi", age: 15, hobby: "playing a game"},
   1: {name: "Judi", age: 15, hobby: "swimming"},
   2: {name: "Judi", age: 15, hobby: "playing a basketball"},
   3: {name: "Jedi", age: 14, hobby: "coding"},
   4: {name: "Jedi", age: 14, hobby: "reading"},
   5: {name: "Jedi", age: 14, hobby: "listen to the music"},
]

我想让我的数据看起来像这样:

[
   0: {name: "Judi", age: 15, hobby: "playing a game, swimming, playing a basketball"},
   0: {name: "Jedi", age: 14, hobby: "coding, reading, listen to the music"},
]

如何对我的数据进行这样的分组?

php laravel concatenation grouping delimited
2个回答
2
投票

如果“名称”字段是标识符,您可以使用一些 Collection 方法来完成此操作:

collect($data)->groupBy('name')->map(function ($group) {
    return ['hobby' => $group->pluck('hobby')->join(', ')] + $group->first();
})->values();

这假设您的数据是数组的数组。

Laravel 8.x 文档 - 集合 - 创建集合

collect

Laravel 8.x 文档 - 集合 - 可用方法 :


2
投票

这确实是一个非常简单的迭代和新数组的构建。像这样的东西。

<?php

$array = [
    ['name' => 'Judi', 'age' => 15, 'hobby' => 'playing a game'],
    ['name' => 'Judi', 'age' => 15, 'hobby' => 'swimming'],
    ['name' => 'Judi', 'age' => 15, 'hobby' => 'playing a basketball'],
    ['name' => 'Jedi', 'age' => 14, 'hobby' => 'coding'],
    ['name' => 'Jedi', 'age' => 14, 'hobby' => 'reading'],
    ['name' => 'Jedi', 'age' => 14, 'hobby' => 'listen to the music'],
];

$result = [];

foreach ($array as $item) {
    $key = $item['name'] . $item['age'];
    if (!array_key_exists($key, $result)) {
        $result[$key] = [
            'name'  => $item['name'],
            'age'   => $item['age'],
            'hobby' => '',
        ];
    }

    $result[$key]['hobby'] = $result[$key]['hobby'] ? $result[$key]['hobby'] . ', ' . $item['hobby'] : $item['hobby'];
}

var_dump(array_values($result));
© www.soinside.com 2019 - 2024. All rights reserved.