【问题标题】:How to prepend item to laravel lists collection without reindexing?如何在不重新索引的情况下将项目添加到 laravel 列表集合中?
【发布时间】:2016-08-21 01:17:39
【问题描述】:

试图将集合传递给视图中的表单选择。 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;
}

【问题讨论】:

    标签: php laravel oop collections


    【解决方案1】:

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

    $companies->prepend('Select a company', 0);
    return $companies;
    
     \*
      * {
      *     "0": "Select a company",
      *     "3": "Test 123 ",
      *     "4": "wer"
      * }
      *\
    

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 2016-06-02
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      相关资源
      最近更新 更多