我正在从Facebook响应构建一个集合。
$ads = new \Illuminate\Support\Collection;
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.
}如果这是一个数组,我会这样做:
$ads[$insight[$key]]['spend'] += $insight[AdsInsightsFields::SPEND];我怎样才能在收藏中做到这一点?
发布于 2018-09-27 23:22:02
为了解决这个问题,我编写了能够执行所需更新的宏。
// Set a single value by dot notation key.
Collection::macro('set', function ($key, $new) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
array_set($current, $key, $new);
} else {
$current = $new;
}
$this->put($primary_key, $current);
});
// Increment a single value by dot notation key.
Collection::macro('increment', function ($key, $amount) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
$new = array_get($current, $key, 0);
$new += $amount;
array_set($current, $key, $new);
} else {
$current += $amount;
}
$this->put($primary_key, $current);
});
// Decrement a single value by dot notation key.
Collection::macro('decrement', function ($key, $amount) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
$new = array_get($current, $key, 0);
$new -= $amount;
array_set($current, $key, $new);
} else {
$current -= $amount;
}
$this->put($primary_key, $current);
});有了这个,我所要做的就是:
$ads->increment($insight[$key] . '.spend', $insight[AdsInsightsFields::SPEND]);如果我想简单地设置一个值,无论键是否存在,我都可以这样做:
$ads->set($insight[$key] . '.spend', $insight[AdsInsightsFields::SPEND]);发布于 2018-09-27 01:45:57
$ads->{$insight[$key]}['spend'] += $insight[AdsInsightsFields::SPEND];这看起来有点奇怪,但您需要以对象属性->propertyName的形式访问第一部分,从数组$insight[$key]中获取的属性名称,因此您需要在它周围加上括号,最后您需要请求一个带有[spend]的属性的数组键。
发布于 2018-09-27 02:56:09
首先,这是数组的集合(不是集合的集合)。
您的问题是如何在集合中获取特定的键值对,
--答案是集合上的'get()‘函数,现在您可以简单地增加’‘值,如下所示。
$ads->get($insight[$key])['spend'] += $insight[AdsInsightsFields::SPEND];注意事项
如果您需要整件事情都是集合,请更新代码以生成一个集合,如下所示
$ads->put($insight[$key], collection([
'add_id' => $insight[AdsInsightsFields::AD_ID],
'ad_name' => $insight[AdsInsightsFields::AD_NAME],
'ctr' => (float)$insight[AdsInsightsFields::CTR],
'spend' => (float)$insight[AdsInsightsFields::SPEND],
]);然后,您可以按如下所示增加支出价值。
$ads->get($insight[$key])->spend += $insight[AdsInsightsFields::SPEND];https://stackoverflow.com/questions/52528221
复制相似问题