Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a collection from a multidimensional array?

I'm trying to make a collection from some arrays of data:

$myCollection = collect(
    ['product_id' => 1, 'price' => 200, 'discount' => '50'],
    ['product_id' => 2, 'price' => 400, 'discount' => '50']
);

When I loop out I would like to do:

foreach ($myCollection as $product) {
    echo $product->price;
    echo $product->discount;
}

But the underlying elements appear to still be in an arrays format, how can I achieve the above output?

like image 259
panthro Avatar asked Dec 03 '22 23:12

panthro


2 Answers

If you want the inner arrays to be a collection, then you can do so as follows:

$myCollection = collect([
    ['product_id' => 1, 'price' => 200, 'discount' => '50'],
    ['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
    return collect($row);
});

If you want the inner arrays to be objects, then you can do as follows:

$myCollection = collect([
    ['product_id' => 1, 'price' => 200, 'discount' => '50'],
    ['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
    return (object) $row;
});

You can also iterate over each of the results...

$myCollection = collect([
    ['product_id' => 1, 'price' => 200, 'discount' => '50'],
    ['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
    return (object) $row;
})->each(function($row) {
    echo sprintf('ProductId: %d, Price: %d, Discount: %s'.PHP_EOL, $row->product_id, $row->price, $row->discount);
});

Output:

ProductId: 1, Price: 200, Discount: 50
ProductId: 2, Price: 400, Discount: 50
like image 127
Gravy Avatar answered Dec 11 '22 17:12

Gravy


Simple as you are getting a collection of an associative arrays because you are collecting arrays elements, so the collection helper doesn't want to modify it in case you need it as array.

Knowing this, if you want to collect objects you should pass an element of object type.

You can cast object data type into the array, like this:

$myCollection = collect( (object) array(
     (object)  ['product_id' => 1, 'price' => 200, 'discount' => '50'],
     (object)  ['product_id' => 2, 'price' => 400, 'discount' => '50'])
);

Then you have a collection of objects !

like image 24
Troyer Avatar answered Dec 11 '22 15:12

Troyer