首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开关函数输出默认值而不是期望值

开关函数输出默认值而不是期望值
EN

Stack Overflow用户
提问于 2017-12-13 13:31:40
回答 3查看 43关注 0票数 3

我试着用下面的代码做一个简单的切换函数。

代码语言:javascript
复制
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and 
Event='$5,000 Novice'  and herd='2' and scratched IN('n','l')  ORDER BY Draw 
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
    die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) { 
    switch($catch) 
    { 
        case '2': 
            return 'Herd Change'; 
        break; 
        default: 
            return 'Damn!'; 
        break; 
    } 
} 
$catch = $row["herd"];
echo "<tr>";
echo "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
echo "<td bgcolor=#FFFFFF>&nbsp;</td>";
echo "</tr>";
?>

我的结果是打印出缺省值“该死!”我做错了什么,而不是期望的值“羊群改变”。如果行herd的值= 2,我想打印出单词"Herd Change“。

EN

回答 3

Stack Overflow用户

发布于 2017-12-13 13:34:25

这很可能是一个类型转换问题

试一试

$catch = string($row["herd"]);并确保$catch为2

票数 3
EN

Stack Overflow用户

发布于 2017-12-13 14:04:48

您的代码应按如下方式进行更改。

代码语言:javascript
复制
<?php 
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and 
Event='$5,000 Novice'  and herd='2' and scratched IN('n','l')  ORDER BY Draw 
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
    die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) { 
    switch($catch) 
    { 
        case '2': 
            return 'Herd Change'; 
        break;
        default: 
            return 'Damn!'; 
           //Break doesn't require in default case
    } 
}

//here you need to get results set from $result.
$html = "";
while ($row = mysqli_fetch_row($result)) {
     $catch = $row["herd"];

     $html += "<tr>";
     $html += "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
     $html += "<td bgcolor=#FFFFFF>&nbsp;</td>";
     $html += "</tr>";  
}
echo $html;
//It will print multiple rows, If query returns multiple rows.
?>
票数 1
EN

Stack Overflow用户

发布于 2017-12-13 13:41:57

如果您的变量$catch包含整数值,则使用以下语法。

代码语言:javascript
复制
switch($catch){
  case 2:
     // your code
  default:
     // your code
}

如果是字符串值,请执行以下操作,

代码语言:javascript
复制
switch($catch){
  case "2":
     // your code
  default:
     // your code
}

Switch case manual

手动对变量进行类型转换不是一种好的做法。

我希望它能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47786156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档