You can use collect(array $array) function.
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!
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",
},
],
},
],
],
}
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);
}
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.
I actually got surprised that i couldn't find a cleaner way of doing this.
So i've done it for my self and pasted it here https://gist.github.com/brunogaspar/154fb2f99a7f83003ef35fd4b5655935
Suggestions are welcome.
Hope it helps.
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.
Please or to participate in this conversation.