Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andysoa's avatar

Recursive conversion of array to collection

Is there any native function on L5 that converts recursively a multidimensional array to a collection?

Thanks for the help!

0 likes
7 replies
crnkovic's avatar

You can use collect(array $array) function.

2 likes
andysoa's avatar

What I want is to have nested collections from a multidimensional array so I can access them as like Eloquent Models.

In the example bellow I would like to be able to do: $collection->first()->results->first() instead of $collection->first()['results']->first()

Check this example:

=> Illuminate\Support\Collection {#875
     all: [
       [
         "search" => "602820",
         "type" => 1,
         "results" => Illuminate\Database\Eloquent\Collection {#860
           all: [
             App\Product {#867
               brand_id: "0",
               sku: "0/602820",
               description: "JG CAL?OS",
               price: "14.55",
               supplier_family: "099",
               search_number: "602820",
             },
             App\Product {#868
               brand_id: "28",
               sku: "28/602820",
               description: "Past Trav Audi A1 / A1 Sportback (10-)",
               price: "14.77",
               supplier_family: "028001",
               search_number: "602820",
             },
           ],
         },
       ],
     ],
   }
1 like
AdamEsterle's avatar

Does this work? I nice little recursive function that will convert arrays of arrays to collections of collections

function r_collect($array)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = r_collect($value);
                $array[$key] = $value;
            }
        }

        return collect($array);
    }
10 likes
defayeke's avatar

This does actually seem like an annoying drawback IMO. When you collect() a multi-dimensional array, like you, I expect it to be a fully traversable collection as if it were object-like, not array-like, whilst still having collection methods available at every refinement. IMO when you collect something, you expect it to be traversable in an object-like way.

1 like
Nospoon's avatar

Great job @brunog . I also think this should be the default behaviour, or at least there should be an option to provide a boolean flag to the collect() helper to make it recursive.

1 like

Please or to participate in this conversation.