简体   繁体   中英

How to grouping an sub array in one column php

I have array like this:

[
   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"},
]

and I wanna make my data look like this:

[
   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"},
]

How to group my data like that? Thank You

It's really a pretty straightforward iteration and building up of a new array. Something like this.

<?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));

If the 'name' field is the identifier you can accomplish this with a few Collection methods:

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

This assumes your data is an array of arrays.

Laravel 8.x Docs - Collections - Creating Collections collect

Laravel 8.x Docs - Collections - Available Methods :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM