【问题标题】:PHP switch statement always pick default or random case when using arrayPHP switch 语句在使用数组时总是选择默认或随机大小写
【发布时间】:2019-06-24 14:45:00
【问题描述】:

我正在使用 switch 从数组中读取具有特定键的值。该数组有 2 种值,int (0-9) 和 hex (0-e)。当我尝试读取 int 时,我的开关总是默认运行。当我尝试返回所述数据时,它返回 1 并且我有案例 1 但开关运行默认值。

我已尝试更改为 if-else 错误为 0,但仍然无法正常工作。我试图强制它使用 (string)$paramapi 字符串并将 case 值更改为 case '1' 并且仍然无法正常工作。我也尝试使用 (integer)$paramapi 和 (int)$paramapi 将它传递给整数,而案例 1 仍然无法正常工作。

请注意,我的 swich 变量在每个 ...

上都保持不变
    $paramapi = trim($parraya[1]);
    $paramid = trim($parraya[2]);
    $param1 = trim($parraya[3]);
    ...
    $paramapi=settype($paramapi,"string");
        switch($paramapi){
            case '1':
                $param1 = $param1."%";
                $db = new DbOperation();
                $result = $db->addLogin(
                    $paramid,
                    $param1
                );
                if($result){
                    $response['error'] = false; 
                    $response['message'] = 'login success';
                }else{
                    $response['error'] = true; 
                    $response['message'] = 'login failed';
                }
            break;
            case '2':
            ...         
            break;

            case '3':
            ...
            break;

            case '4':
            ...
            break;

            case '5':
            ...
            break;

            case '6':
            ...
            break;

            case '7':
            ...
            break;

            default:
                $response['error'] = true; 
                $response['message'] = 'Invalid API Call'.' '.$aparraya[1];    
    }

我得到“无效的 API 调用 1”,想要得到“登录成功”或“登录失败”

我将 $paramapi=settype($paramapi,"string"); 更改为 settype($paramapi,"string"); 这修复了我在强制我的值字符串时发现的一些新错误。 我也变了

default:
    $response['error'] = true; 
    $response['message'] = 'Invalid API Call'.' '.$aparraya[1];    
}

default:
    $response['error'] = true; 
    $response['message'] = 'Invalid API Call'.' '.$paramapi;    
}

仍然得到“无效的 API 调用 1”

我的代码现在可以工作了。原来我的错误是因为我忘了保存它。

【问题讨论】:

  • var_dump($paramapi);,这是什么?
  • 使用像Visual Studio Code这样的IDE,你能不能调试和确认$paramapi里面的数据?
  • 去掉settype
  • $paramapi=settype($paramapi,"string"); 尝试var_dump($paramapi);gettype($paramapi); 之后,你能用结果编辑你的问题吗?

标签: php string post switch-statement hex


【解决方案1】:

函数settype 返回一个布尔值,因此$paramapi 将始终为truefalse。您不需要将settype 的结果放回$paramapi。它只需调用该函数即可为您做到这一点。

因此,将$paramapi=settype($paramapi,"string"); 更改为settype($paramapi,"string");,它应该可以工作。

(https://www.php.net/manual/en/function.settype.php)

【讨论】:

  • 这在技术上是正确的答案,因为我在编辑后忘记保存我的 PHP。你的回答使我的开关工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多