【问题标题】:How to put php array into a html form?如何将php数组放入html表单?
【发布时间】:2021-05-29 23:42:24
【问题描述】:
$countryList = array(
    'Russia'        => 'Moscow',
    'US'        => 'United States');

我有这个数组,我正在尝试将其生成到一个 hmtl 表单上,该表单将具有这样的输出。

<select name='country'>
    <option value='0'>Russia - St.Petersburg</option>
    <option value='1'>United States - Dallas</option>
    ...
</select>

任何事情都将不胜感激。

【问题讨论】:

  • 您的 $countryList 数据与您在 SELECT HTML sn-p 中显示的示例数据不匹配。 OPTION 标记的“值”部分也必须来自数组。

标签: php html arrays forms


【解决方案1】:

通过一个简单的循环,array_flip/array_keys 获取国家/地区的索引地图:

<?php
$countryList = [
    'Russia' => 'Moscow',
    'US'     => 'United States'
];
$countryKeys = array_flip(array_keys($countryList));
?>
<select name='country'>
<?php foreach ($countryList as $country => $city): ?>
    <option value='<?= $countryKeys[$country] ?>'><?= $country ?> - <?= $city ?></option>
<?php endforeach; ?>
</select>

结果:

<select name='country'>
    <option value='0'>Russia - Moscow</option>
    <option value='1'>US - United States</option>
</select>

俄罗斯 - 圣彼得堡美国 - 达拉斯 不在列表中,因为它不在数组中。

【讨论】:

    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多