PHP选项值 [英] Php option value

查看:58
本文介绍了PHP选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个区域列表(1000多个),我想知道是否有一种方法可以使我更轻松地使用代码而不是重复每个值.

I have a list of areas (1000+) and i was wondering if there was a way i can do this easier with code instead of repeating each value.

<select>
<option value="apple" <?php if ($user_data["$area"] == apple){echo 'selected';} ?>>Apple
</option> 

<option value="lemon" <?php if ($user_data["$area"] == lemon){echo 'selected';} ?>>Lemon
</option> 

<option value="orange" <?php if ($user_data["$area"] == orange){echo 'selected';} ?>>Orange
</option> 

<option value="banana" <?php if ($user_data["$area"] == banana){echo 'selected';} ?>>Banana
</option>
</select>

I.E.每个选项都有相同的php代码,而不必每次都键入值的名称

I.E. have the same piece of php code for each option instead of having to type in the name of the value each time

<?php if ($user_data["$area"] == option VALUE){echo 'selected';} ?>

您能为教程中的内容提供一些代码或想法吗,我不知道如何开始.谢谢!

Could you provide some code or ideas for what to look in tutorials, i have no idea how to start. Thank you!

推荐答案

使用数组:

$areas = array(
    'apple' => 'Apple',
    'lemon' => 'Lemon',
    'orange' => 'Orange',
    'banana' => 'Banana'
);

然后使用该数组打印选择内容:

Then use that array to print the select:

<select>
<?php foreach ($areas as $value => $text): ?>
    <option value="<?php echo $value; ?>" <?php if ($user_data[$area] == $value) {echo 'selected';} ?>><?php echo $text; ?>
    </option> 
<?php endforeach; ?>
</select>

我使用的是关联数组,因为我假设您希望能够自定义区域的文本标签,并且它们将不仅是用于匹配用户数据的值的大写版本.

I am using an associative array because I am assuming that you want to be able to customize the areas' text label, and that they will not only be a capitaized version of the value used to match the user data.

这篇关于PHP选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆