I am building a collection from a Facebook API response.
$ads = new IlluminateSupportCollection;
if (!$ads->has($insight[$key])) {
$ads->put($insight[$key], [
'ad_id' => $insight[AdsInsightsFields::AD_ID],
'ad_name' => $insight[AdsInsightsFields::AD_NAME],
'ctr' => (float)$insight[AdsInsightsFields::CTR],
'spend' => (float)$insight[AdsInsightsFields::SPEND],
]);
} else {
// Increment spend value here.
}
If this were an array, I’d just do this:
$ads[$insight[$key]]['spend'] += $insight[AdsInsightsFields::SPEND];
How do I do that on a Collection?
3
Answers
To solve this I wrote macros capable of performing the updates needed.
With this, all I need to do is something like:
If I want to simply set a value, whether the key exists or not, I can do this:
It’s a little weird looking but you need to access the first part as an object property
->propertyName
, that property name you’re grabbing from an array$insight[$key]
so you need to throw brackets around it, finally you need to ask for an array key of that property with[spend]
at the end.first thing, this is a collection of arrays (not a collection of collection).
your question was how to get a particular key value pair in a collection,
The Answer is ‘get()’ function on collection.
now you can simply increment the ‘spend’ value as below.
NOTE
if you need whole thing to be collections, Update your code to make a collection of collection as below
then you can increment spend value as below.