0

这很简单,但我无法进入逻辑。

有一个简单的在线表格。希望提交后能够调整变量。

如果有人可以阐明这一点,将非常感激!

$chocolatebar = $HTTP_POST_VARS['chocolatebar'];

if $chocolatebar = "a"  then we want to change the value to "snickers";

if $chocolatebar = "b"  then we want to change the value to "mars";

if $chocolatebar = "c"  then we want to change the value to "cherry ripe"; 
4

7 回答 7

3
$chocolatebar = isset($_POST['chocolatebar']) ? $_POST['chocolatebar'] : '';
if ($chocolatebar == "a")  $chocolatebar = "snickers";
elseif ($chocolatebar == "b")  $chocolatebar = "mars";
elseif ($chocolatebar == "c")  $chocolatebar = "cherry ripe"; 
于 2012-11-02T05:55:09.957 回答
1
$chocolatebar = $POST['chocolatebar'];

if($chocolatebar =="a")
{ 
     $chocolatebar="snickers";
}
else if($chocolatebar =="b")
{ 
    $chocolatebar="mars";
}
else
{ 
    $chocolatebar="cherry ripe";
}
于 2012-11-02T05:56:45.927 回答
1

首先不要使用$HTTP_POST_VARS,此功能已弃用$HTTP_POST_VARS

另外,我猜你应该使用 switch 而不是 if-else。

<?php
$chocolatebar = ($_POST['chocolatebar'] != '') ? $_POST['chocolatebar'] : '';

switch($chocolatebar){
    case 'a':
        $chocolatebar = 'snickers';
        break;

    case 'b':
        $chocolatebar = 'mars';
        break;

    case 'c':
        $chocolatebar = 'cherry ripe';
        break;

    default:
        $chocolatebar = '';
        break;
}

echo $chocolatebar;
于 2012-11-02T06:06:57.383 回答
0

在这种情况下,当您有多个选项时,您最好使用switch多个if-else.

if(isset($_POST['chocolatebar'])){
    $chocolatebar = $_POST['chocolatebar'];
    switch ($chocolatebar) {
        case "a":
            $chocolatebar = "snickers";
            break;
        case "b":
            $chocolatebar = "mars";
            break;
        case "c":
            $chocolatebar = "cherry ripe";
            break;
    }
}
于 2012-11-02T06:01:26.113 回答
0
$chocolatebar = $_POST['chocolatebar'];
switch($chocolaterbar){
    case "a": 
        $chocolatebar = "snickers";
    break;

    case "b": 
        $chocolatebar = "mars";
    break;

    case "c": 
        $chocolatebar = "cherry ripe";
    break;

    default:
        $chocolatebar = "unknown";
    break;
}

我的目的是使用开关。或者另一种聪明的选择是使用数组..

$all_chocolates = array("a"=>"snickers","b"=>"mars","c"=>"cherry ripe");
$chocolatebar = $_POST['chocolatebar'];
$chocolatebar = isset($all_chocolates[$chocolatebar]) ? $all_chocolates[$chocolatebar] : "unknown";
于 2012-11-02T06:02:37.127 回答
0

如果您想更改更多值,也可以使用 switch case。

于 2012-11-02T06:03:29.037 回答
0

为方便起见,您需要在键与值之间建立映射。

$valueMap = array(
    'a' => 'snickers',
    'b' => 'mars',
    'c' => 'cherry ripe'
);

// The '@' sign prevents error if characters other than
// 'a', 'b', 'c' is provided, $value will be NULL in
// those cases.
$value = @$valueMap[$_POST['chocolatebar']];
于 2012-11-02T06:03:43.143 回答