Laravel collections

méthode chunk()

Quand est apparue cette méthode ?

depuis Laravel < v5.1

Description


Exemples

Il y a 1 exemple pour cette collection

Exemple #1 : Découper la collection languages en petites collections de 3 éléments maxi

Collection utilisée

    
        // define languages collection
        $this->languages = collect([
            'php',
            'python',
            'javascript',
            'go',
            'c#',
            'java',
            'cobol',
            'basic'
        ]);

        Illuminate\Support\Collection {#413 ▼
            #items: array:8 [▼
                0 => "php"
                1 => "python"
                2 => "javascript"
                3 => "go"
                4 => "c#"
                5 => "java"
                6 => "cobol"
                7 => "basic"
            ]
        }
    

Code source


$languages = collect([
            "php",
            "python",
            "javascript",
            "go",
            "c#",
            "java",
            "cobol",
            "basic"
            ]);

$chunked_languages = $languages->chunk(3);
print_r($chunked_languages);

Résultat

    
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => php
                            [1] => python
                            [2] => javascript
                        )

                )

            [1] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [3] => go
                            [4] => c#
                            [5] => java
                        )

                )

            [2] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [6] => cobol
                            [7] => basic
                        )

                )

        )

)