gpt4 book ai didi

php - 如何在不重新索引的情况下将项目添加到 laravel 列表集合中?

转载 作者:可可西里 更新时间:2023-11-01 13:20:45 24 4
gpt4 key购买 nike

试图将一个 collectino 传递给 View 中的表单选择。 prepend 方法正在重新索引集合,我丢失了正确的公司 ID。

$companies = Company::lists('name','id');
return $companies;

/*
* {
* "3": "Test 123 ",
* "4": "wer"
* }
*/

$companies->prepend('Select a company');
return $companies;

/*
* [
* "Select a company",
* "Test 123 ",
* "wer"
* ]
*/

我现在在 prepend 方法中查看 Collection 对象,它是:

public function prepend($value, $key = null)
{
$this->items = Arr::prepend($this->items, $value, $key);

return $this;
}

最佳答案

好的,我很快找到了解决方案。通过为第二个参数传递 key ,我使用 0,该方法将保留原始 key 。

$companies->prepend('Select a company', 0);
return $companies;

\*
* {
* "0": "Select a company",
* "3": "Test 123 ",
* "4": "wer"
* }
*\

关于php - 如何在不重新索引的情况下将项目添加到 laravel 列表集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com