我有一个存储服务器地址的数组
$servers = array(
'UK'=>array(
'voi' => '54.53.23.32',
'gps' => '55.65.34.34',
'sos' => '54.54.34.23'
),
'USA'=>array(
'voi' => '12.23.45.67',
'gps' => '65.443.23.45',
'sos' => '12.23.456.4'
)
);
我有一个列出服务器位置的表单
<select name="server" id="server">
<?php foreach($servers as $key => $arr){
echo "<option>" .$key. "</option>"; }
?>
</select>
提交表单后,我需要使用正确的国家/地区IP
设置会话变量$_SESSION['voi']=$submitted_countrys_voi_ip;
$_SESSION['gps']=$submitted_countrys_gps_ip;
等。
如何根据表单发布选择正确的密钥,并将子数组中的值转换为会话变量?
答案 0 :(得分:1)
首先,您选择没有值。所以先修复了
<select name="server" id="server">
<?php foreach($servers as $key => $arr){
echo "<option value='$key'>" .$key. "</option>"; }
?>
</select>
然后,提交表单后。 假设使用POST方法提交表单
$server = ..; //Being your array of ips
$sub_server = $_POST['server']; //get the submitted server
$_SESSION['voi'] = $server[$sub_server]['voi'];
$_SESSION['gps'] = $server[$sub_server]['gps'];
// and so on
如果你有一个国家的大量IP,那么你可能想先创建一个类型的数组。
$server = ..;
$types = array('voi','gps', 'sos'); //TYPES in a single array
$sub_server = $_POST['server'];
foreach($types as $type) {
$_SESSION[$type] = $server[$sub_server][$type];
}
这会自动分配每种类型。
答案 1 :(得分:0)
假设您正在使用<form method="POST"
,您可以执行类似
if ( isset($_POST['server']) ) {
$key = $_POST['server'];
if ( !isset( $servers[$key] ) {
die('unknown server');
}
$_SESSION['server'] = $servers[$key];
echo 'voi=', $_SESSION['server']['voi'];
}
else {
die('no server key found in request');
}
答案 2 :(得分:0)
试试这个:
$_SESSION['voi']=$servers[$_POST['server']]['voi'];
$_SESSION['gps']=$servers[$_POST['server']]['gps'];
答案 3 :(得分:0)
$country = $_POST['server'];
if (isset($servers[$country])) {
$_SESSION['voi'] = $servers[$country]['voi'];
$_SESSION['gps'] = $servers[$country]['gps'];
}
else {
// Unknown country
}