简体   繁体   中英

Search array key from form post and get sub array

I have an array which is storing server addresses like so

$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'
  )
);

I have a form which is listing the server locations

<select name="server" id="server">
<?php foreach($servers as $key => $arr){
echo "<option>" .$key. "</option>"; }
?>
</select>

Once the form is submitted i need to set a session variable with the correct countrys IP's

$_SESSION['voi']=$submitted_countrys_voi_ip;
$_SESSION['gps']=$submitted_countrys_gps_ip;

etc..

How can i choose the correct key based on the form post and get the values from the sub array into a session variable?

First of all, you select does not have a value. So fixed that first

<select name="server" id="server">

    <?php foreach($servers as $key => $arr){
    echo "<option value='$key'>" .$key. "</option>"; }
    ?>

</select>

Then, after the form is submitted. Assuming that form is submitted using POST method

$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

Improvement

In case you have lots of IP's for a nation, then you might want to create an array of the types first.

$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];
}

This is automatically assign every types at once.

Assuming that you're using <form method="POST" you could do something like

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');
}

Try this:

$_SESSION['voi']=$servers[$_POST['server']]['voi'];
$_SESSION['gps']=$servers[$_POST['server']]['gps'];
$country = $_POST['server'];
if (isset($servers[$country])) {
  $_SESSION['voi'] = $servers[$country]['voi'];
  $_SESSION['gps'] = $servers[$country]['gps'];
}
else {
  // Unknown country
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM