Reputation: 4007
I have response like:
Array (
[0] => Array (
[0] => Array (
[Product] => 'Product1'
[Total] => $10
)
[1] => Array (
[Product] => 'Product2'
[Total] => $50
)
)
[1] => Array (
[0] => Array (
[Product] => 'Product1'
[Total] => $20
)
[1] => Array (
[Product] => 'Product2'
[Total] => $30
)
)
[2] => Array (
[0] => Array (
[Product] => 'Product1'
[Total] => $0
)
[1] => Array (
[Product] => 'Product2'
[Total] => $10
)
)
)
I want to get array of Total
of Product1
but only using laravel collection.
I have tried :
$data = [];
$collection = collect($monthly_usage_data)->each(function ($item, $key) {
$data['Total'][$key] = str_replace('$', '', collect($item)->where('Product', 'Product1')->pluck('Total'));
echo str_replace('$', '', collect($item)->where('Product', 'Product1')->pluck('Total'));
});
When i print $data it shows blank array; When i echo inside each it ll give ["10"]["20"]["0"]
.
Can somebody tell me right way to use collection to get array of total
of product1
Upvotes: 0
Views: 860
Reputation: 3679
generally you can use this :
$totals = $collection->where('Product', 'Product1')->mapWithKeys(function ($item) {
return $item['Total'];
});
$totals->all();
Upvotes: 0
Reputation: 35337
Remember that functions have their own scopes. $data in the global scope is not the same as $data inside your function unless you import it.
You can import variables into anonymous functions with use:
function ($item, $key) use ($data) {
}
Upvotes: 1