【问题标题】:PHP if function with multiple outcomes [duplicate]PHP if函数具有多个结果[重复]
【发布时间】:2018-01-17 13:53:55
【问题描述】:

我正在尝试根据它所在的部门返回不同的属性状态。有销售和租赁部门,每个部门都有一个数字系统表示属性的状态。

我尝试使用 if 函数来查询每个属性的部门和状态,并为每个状态返回不同的文本字符串,但是所有属性都标记为“暂停”(即第一个选项)

代码如下。这不是特别优雅,抱歉。

function prop_status( $dept = null, $availability = null) {
if ( $dept = "Lettings" and $availability = "1") {
  return "On hold";
}
if ( $dept = "Lettings" and $availability = "2") {
  return "For rent";
}
if ( $dept = "Lettings" and $availability = "3") {
  return "References pending";
}
if ( $dept = "Lettings" and $availability = "4") {
  return "Let agreed";
}
if ( $dept = "Lettings" and $availability = "5") {
  return "Let";
}
if ( $dept = "Sales" and $availability = "1") {
  return "On hold";
}
if ( $dept = "Sales" and $availability = "2") {
  return "For sale";
}
if ( $dept = "Sales" and $availability = "3") {
  return "Under offer";
}
if ( $dept = "Sales" and $availability = "4") {
  return "Sold STC";
}
if ( $dept = "Sales" and $availability = "5") {
  return "Sold";
}
if ( $dept = "Sales" and $availability = "7") {
  return "Withdrawn";
}

非常感谢您对这项工作的任何帮助。

【问题讨论】:

  • = 在 if 中应该是 ==
  • 你不是在比较,你是在分配,你需要=====而不是=
  • 我将声明一个多维查找数组来避免所有这些条件。 $lookup['Lettings']['1']='On hold',...
  • 谢谢大家。 Mickmackusa 我目前不明白这意味着什么(对 PHP 来说很新),但会调查一下,谢谢。

标签: php xml if-statement logic


【解决方案1】:

您应该将所有= 更改为==

function prop_status( $dept = null, $availability = null) {
if ( $dept == "Lettings" and $availability == "1") {
  return "On hold";
}
if ( $dept == "Lettings" and $availability == "2") {
  return "For rent";
}
if ( $dept == "Lettings" and $availability == "3") {
  return "References pending";
}
if ( $dept == "Lettings" and $availability == "4") {
  return "Let agreed";
}
if ( $dept == "Lettings" and $availability == "5") {
  return "Let";
}
if ( $dept == "Sales" and $availability == "1") {
  return "On hold";
}
if ( $dept == "Sales" and $availability == "2") {
  return "For sale";
}
if ( $dept == "Sales" and $availability == "3") {
  return "Under offer";
}
if ( $dept == "Sales" and $availability == "4") {
  return "Sold STC";
}
if ( $dept == "Sales" and $availability == "5") {
  return "Sold";
}
if ( $dept == "Sales" and $availability == "7") {
  return "Withdrawn";
}

查看php中的比较运算符here

$a == $b 如果 $a 等于 $b,则返回 TRUE

$a === $b 如果 $a 等于 $b,则返回 TRUE,并且它们属于同一类型。

【讨论】:

  • 大侠,谢谢。似乎是一个令人尴尬的基本错误,哎呀..
  • @ChrisL 别担心,大多数程序员都会犯同样的错误。下次当您在 SO 中提出问题时请记住。顺便说一句,对于那些来自 SEO 的人来说,这是对您问题的回答。
  • 刚刚接受了您的回答。才意识到我收到了通知。
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 2019-07-31
  • 1970-01-01
  • 2012-06-08
  • 2017-09-28
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多