mon*_*onk 9 php mysql arrays laravel
我正在尝试将新数组项推送到包含数据库项的现有数组变量中.我想要做的是在这个数组的末尾添加一个名为"Others"的新项目,并将其显示为视图中的select下拉列表,其中包含来自数据库的所有项目,并在此末尾选择"其他"项目我手动添加到我的控制器中.
这是我试图做的:
$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;
}
Run Code Online (Sandbox Code Playgroud)
它说的是这样的
未处理的异常
信息:
试图获取非对象位置的属性:
第104行的C:\ xampp\htdocs\khelkheladi\khelkheladi\application\controllers\_register.php
在我的数据库中,竞赛有这种类型的列结构
->id
->year
->place
->name
->created_at
->updated_at
Run Code Online (Sandbox Code Playgroud)
在给定的顺序.
我想要做的是没有实际在数据库中插入项目,只是静态地显示视图中选择标记中的其他选项.如何插入这样的新项目而不将其实际插入数据库但仅在视图中显示?
通过检索数据库项目我之前得到的输出是这样的
<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>
Run Code Online (Sandbox Code Playgroud)
我喜欢做的就是这样
<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>
Run Code Online (Sandbox Code Playgroud)
那是因为你要在数组的最后一个元素中添加一个非对象.
在这里,我想你得到一个名为property的对象数组
$competition_all = Competition::all();
Run Code Online (Sandbox Code Playgroud)
在这里,您将一个key => value对添加到objects数组的最后一个元素
$newCompete = array('name'=>'Others');
array_push($competition_all, $newCompete);
Run Code Online (Sandbox Code Playgroud)
在这里,您可以浏览对象数组,当涉及到最后一个元素时,"$ competition_games-> name"没有名称属性
foreach ($competition_all as $competition_games) {
$this->competition_games[$competition_games->name] = $competition_games->name;
}
Run Code Online (Sandbox Code Playgroud)
尝试像stdclass这样的东西:
$newCompete = new StdClass();
$newCompete->name = 'Others';
array_push($competition_all, $newCompete);
Run Code Online (Sandbox Code Playgroud)
执行此操作的“干净”方法是创建一个实例Competition
而不将其提交到数据库,然后使用额外的实例再次重复您的循环。
但是,这里您似乎只是生成一个列表,因此应该足以更快地添加到最终列表中:
// Empty array
$this->competition_games = [ 0 => 'Others' ];
foreach (Competition::all() as $game) {
$this->competition_games[$game->id] = $game->name;
}
Run Code Online (Sandbox Code Playgroud)
使用 0(或 -1)作为不存在的 Id。
归档时间: |
|
查看次数: |
62131 次 |
最近记录: |