【发布时间】:2017-01-13 06:04:18
【问题描述】:
我正在使用以下对象数组创建一个 HTML 表单选择元素。
Array
(
[0] => stdClass Object
(
[post_title] => Showing Now Review
)
[1] => stdClass Object
(
[post_title] => Interstellar
)
[2] => stdClass Object
(
[post_title] => The Conjuring 2
)
[3] => stdClass Object
(
[post_title] => Django Unchained
)
[4] => stdClass Object
(
[post_title] => Captain America: Civil War
)
[5] => stdClass Object
(
[post_title] => Dallas Buyers Club
)
)
这是一个名为 $reviewTitles 的数组的内容。
然后我想遍历这个,并在选择中显示每个标题的第一个字母。
到目前为止,我已经使用以下代码实现了这一点:
foreach($reviewTitles as $key => $value) {
$fullTitle = $reviewTitles[$key]->post_title;
$firstLetter = substr($fullTitle, 0, 1); ?>
<option value="<?php echo($firstLetter); ?>" <?php echo($_POST[ 'cboTitle']=="<?php echo($firstLetter); ?>" ? "selected='selected'": "")?>>
<?php echo($firstLetter); ?>
</option>
<?php } ?>
但是,使用此代码,如果标题与之前显示的字母相同,它将再次显示在下拉列表中。例如,此时下拉菜单中会显示两个 D。
我想知道如何从选择元素的最终列表中删除任何重复的条目。
任何帮助将不胜感激。
【问题讨论】:
-
为什么使用第一个字母作为选项值?使用其他东西,这样你就不会有重复的问题。
标签: php arrays object foreach key