【问题标题】:How to load the correct data from a select, based on the object value如何根据对象值从选择中加载正确的数据
【发布时间】:2018-03-24 01:31:47
【问题描述】:

这是一个通用的 foreach 循环:

<label>Type:</label>
<select name="postTypeArray">
  <?php foreach ($postTypeArray as $thePostType) : ?>
  <option value="<?php echo $thePostType ?>"><?php echo $thePostType ?></option>
  <?php endforeach; ?>
</select><br/><br/>

当页面加载 postType 时,它​​可以是评论、图像或视频。这是从数据库中加载并存储在 postType 对象中的。问题是,在加载页面时,选择的 postType 总是显示为评论对象,这是 $postTypeArray 中的第一个值,而当我使用selected = "selected" 时,检索到的选定值总是视频,这是最后一个值在 $postTypeArray 中。

我查看了其他答案,尝试了 foreach 中的 if 语句,使用了键值数组等,但尚未找到解决方案。

【问题讨论】:

  • 在选项标签中,我认为你需要 selected="selected" 而不是 value="selected"
  • 哪个变量名包含它应该选择的值?
  • @KarloKokkak 抱歉,我的意思是 selected="selected"

标签: php object select foreach compare


【解决方案1】:

假设您将当前项目的值保存在 $post['type'] 中。

然后您使用selected 属性来选择值。

<label>Type:</label>
<select name="postTypeArray">
<?php foreach ($postTypeArray as $thePostType) : ?>
  <option value="<?= $thePostType ?>"<?= (isset($post['type']) && $post['type'] === $thePostType ? ' selected' : '')?>><?= $thePostType ?></option>
<?php endforeach; ?>
</select>

【讨论】:

  • 谢谢!您的答案是正确的,但请注意详细说明 $post['type'] === $thePostType 的方式? '已选择' : '' 有效吗?谢谢
  • 它就像一个 if/else 语句,它被称为三元组,所以它喜欢执行以下操作但更简洁。 if (isset($post['type']) &amp;&amp; $post['type'] === $thePostType) { echo ' selected'; } else { echo ''; },虽然 else 不需要它的等价物。
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2015-08-30
  • 1970-01-01
  • 2021-04-12
  • 2022-12-09
  • 1970-01-01
相关资源
最近更新 更多