简体   繁体   中英

How can I access a child array in a Laravel Collection?

I have a database search that returns thousands of entries which I then group by two columns like so:

$results = $merged->groupBy(['source', 'parent']);

The result is Laravel Collection with the following structure, grouped first by the 'source' ( 1_k12_fill_trypsin_dig ), then the 'parent' ( 2, 4, 9, 10... ), and each 'parent' has some number of children:

['第 1 组'=> []

I want to sort the parents by the number of children they have. So, in this example, I would want '4' to be at the top, so that the child count serves as the 'truth test' in some closure. I just don't know how to access these elements. I was hoping to use Collection methods as opposed to looping through with vanilla PHP.

Have you tried sorting by their count?

Sort by source count

$merged
    ->groupBy(...)
    ->sort(function ($sources) {
        return collect($sources)->count();
    });

Sort by parent count

$merged
    ->groupBy(...)
    ->sort(function ($sources) {
        return collect($sources)
            ->sum(function ($parents) {
                return count($parents);
            });
    });

To sort only the nested array, you could use map() or transform() .

$merged
    ->groupBy(['source', 'parent'])
    ->map(function ($source) {
        return collect($source)
            ->sortByDesc(function ($parent) {
                return count($parent);
            })
            ->all();
    });

// PHP 7.4+
$merged
    ->groupBy(['source', 'parent'])
    ->map(fn($source) => 
        collect($source)
            ->sortByDesc(fn($parent) => count($parent))
            ->all()
    );

I used Faker to generate collections similar to yours and it worked for me.

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