我正在尝试将新的数组项推入现有数组变量,该变量具有数据库的项目。我要做的是在这个数组结束时添加一个名为'其他'的新项目,并将其显示为选定下拉视图,其中包括来自数据库的所有项目,并在此选择的所有项目中选择“其他项目”我手动添加在我的控制器中。

这是我尝试做的事情:

    $competition_all = Competition::all();
    $newCompete = array('name'=>'Others');
    array_push($competition_all, $newCompete);

    $this->competition_games = array('Competition');

    foreach ($competition_all as $competition_games) {
        $this->competition_games[$competition_games->name] = $competition_games->name;
    }
.

它说的是这个

未处理的异常

消息:

尝试获取非对象位置的属性:

c:\ xampp \ htdocs \ khelkheladi \ khelkheladi \ application \ controllers \ register.php 在线104

在我的数据库中,竞争具有这种类型的列结构

->id
->year
->place
->name
->created_at
->updated_at
.

在给定的顺序。

我在尝试做的是没有实际在数据库中插入项目,只是静态显示其他选择“在”选择“标记中的项目。如何插入此类新项目而不实际将其插入数据库,但仅在视图中显示?

通过只需检索数据库项目之前我得到的输出就像这个

<select>
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
  <option value="3">Value 3</option>
  <option value="4">Value 4</option>
</select> 
.

我喜欢做的就是这样

<select>
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
  <option value="3">Value 3</option>
  <option value="4">Value 4</option>
  <option value="5">Others</option>
</select> 
.

有帮助吗?

解决方案

“clean”方法是要创建生成的一个实例,而无需将其提交给数据库,并使用额外的实例再次重复您的循环。 但是,在这里,您似乎只是生成了一个列表,所以应该足以对最终列表进行更快的添加:

$competition_all = Competition::all();
$this->competition_games = array('Competition');

foreach ($competition_all as $competition_games) {
    $this->competition_games[$competition_games->name] = $competition_games->name;
}
$this->competition_games['name'] = 'Others';
.

其他提示

是因为您正在将非对象添加到数组的最后一个元素。

在这里,我假设您使用名称属性的对象数组

$competition_all = Competition::all();
.

此处将key=>值对添加到对象数组的最后一个元素

$newCompete = array('name'=>'Others');
array_push($competition_all, $newCompete);
.

在这里,您走过了一系列对象,当谈到最后一个元素时,“$ cather_games-> name”没有名称属性

foreach ($competition_all as $competition_games) {
            $this->competition_games[$competition_games->name] = $competition_games->name;
        }
.

尝试类似于包括stdclass的东西:

$newCompete = new StdClass();
$newCompete->name = 'Others';
array_push($competition_all, $newCompete);
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top