【问题标题】:Flow control using if statements使用 if 语句进行流控制
【发布时间】:2015-02-14 17:32:22
【问题描述】:

我有300+ 行数据,这些数据来自我们云应用程序的各个用户。用户在移动设备和计算机上使用 Web 应用程序。由于我们使用的是响应式设计,因此我们很感兴趣,我们知道用户使用什么来访问应用程序。

我们对像这样的知名制造商很感兴趣

<?php
$dbh = new PDO('mysql:host=localhost;dbname=qs', 'qs_root', 'lepasswort');
$fc = $dbh->prepare("select str from test_str");
$fc->execute();

$i = 0;
while($result = $fc->fetch(PDO::FETCH_ASSOC)){

$one = $result['str'];

$cmd = "/usr/bin/perl str_processor.pl  '$one' ";
$output = shell_exec($cmd);
$arr = explode( ',', $output);
$the_type = $arr[0];

if($the_type == 'samsung'){
echo 'samsung';
}

if($the_type == 'nokia'){
echo 'samsung';
}

if($the_type == 'iphone'){
echo 'samsung';
}
if($the_type == 'ipad'){
echo 'samsung';
}
else{
 echo 'exception';
 }
}
?>

知名品牌有samsung,nokia,iphone等。

但是,有很多品牌不为人所知,我们想忽略它们。

我的脚本看起来就像我在上面写的一样,只是我在我的 if 之间留下了实际代码。

当我运行脚本时,我得到exception,这意味着 ifs 中的任何代码都没有被执行。 if 是这里的正确方法吗?

注意:

我已经检查并再次检查了我的 pl 脚本及其正确,所以它不可能是它。

【问题讨论】:

  • 检查每个变量的内容以确保它们包含您所期望的内容。
  • var_dump 您的 $the_type 变量以查看它实际包含的内容。 == 比较区分大小写,不会忽略空格或 NUL 字节。考虑使用 switch 语句或数组映射。
  • 感谢 ceejayoz 和 mario。您的建议最终成功了。
  • 你为什么不直接使用switch($the_type) { case: 'samsung': echo 'samsung'; break; case: 'nokia': echo 'nokia'; break; case 'and-so-on': echo 'and so on'; break; }

标签: php


【解决方案1】:

您必须使用elseif 否则每次终端不是 ipad 时都会出现“异常”。所有条件都是互斥的。

if ($the_type == 'samsung') {
    echo 'samsung';
} elseif ($the_type == 'nokia') {
    echo 'nokia';
} elseif ($the_type == 'iphone') {
    echo 'iphone';
} elseif ($the_type == 'ipad') {
    echo 'ipad';
} else {
   echo 'exception';
}

另一种方法是使用数组:

$models = ['samsung', 'nokia', 'iphone', 'ipad'];

if (in_array($the_type, $models))
    echo $the_type;
else
    echo 'exception';

如果您没有得到除“异常”以外的任何结果,请检查 $the_typevar_dump 以确保它包含您希望的结果。

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多