在laravel中,此方法返回Collection
类型的结果:
$all_currency = CurrencyType::lists('currency_type', 'id');
结果:
Collection {#687 ▼
#items: array:2 [▼
1 => "EUR"
2 => "CHF"
]
}
现在,我想将-1 => "USD"
添加到其中。但我做不到。我的解决方案在其中创建嵌套数组。例如:
$all_currency->push (["-1"=>"11"]);
结果:
Collection {#687 ▼
#items: array:4 [▼
1 => "EUR"
2 => "CHF"
3 => array:1 [▼
-1 => "USD"
]
]
}
如果需要使用数组,可以尝试使用toArray()方法将集合转换为数组:
$all_currency = CurrencyType::pluck('currency_type', 'id')->toArray();
$all_currency['-1'] = '11';
如果您需要使用collection,请使用put()helper:
$all_currency = CurrencyType::pluck('currency_type', 'id')->put('-1', '11');
此外,lists()
已弃用,将来将被删除,请改用pluck()
。
在添加货币之前,是否尝试将集合强制转换为数组?
否则,检查Collection类的接口可能会有所帮助。既然你没有提到它,它可能是教义或Propel或其他什么?
然后你可能会发现,有一个特殊的函数可以添加键值对,因为推送一个值会将该值(在你的情况下是一个数组)添加到集合中,这不是你想要的。
可能无法将值添加到特定的键索引-1中,这完全取决于您实际使用的ORM及其实现。
//编辑:
似乎是正确的方法,代码应该是这样的:
$all_currency->push (-1, "11");
https://laravel.com/api/master/Illuminate/Support/Collection.html#method_put
在集合上使用put()
方法:
$all_currency->put(-1, "USD");
您可以在这里看到所有可用的集合方法:collections