To flatten a multi-dimensional collection in Illuminate/Collections, you can use the flatten()
method provided by the collection object.
Here is an example of how to use the flatten()
method:
use Illuminate\Support\Collection;
// Create a multi-dimensional collection
$collection = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 35],
]);
// Flatten the collection
$flattenedCollection = $collection->flatten();
// Output the flattened collection
$flattenedCollection->each(function ($item) {
echo $item . "\n";
});
In this example, the flatten()
method is called on the $collection
object. This method will flatten the multi-dimensional array into a single-dimensional array. The resulting flattened collection is stored in the $flattenedCollection
variable.
To get the values from the flattened collection, you can use the each()
method or any other collection method like foreach
, map
, etc.
Note: The flatten()
method only flattens one level of nested arrays by default. If you have deeper nested arrays, you can pass a depth argument to specify how many nested levels you want to flatten. For example: $collection->flatten(2)
will flatten two levels of nested arrays.