【问题标题】:If-statement inside foreach, the statement is not applying [duplicate]foreach中的if语句,该语句不适用[重复]
【发布时间】:2017-12-02 10:08:15
【问题描述】:

我正在处理来自 url 的 json 并显示一些数据。问题是我只想显示两个具有特定 ID 的帐户,但是当我执行以下代码时,会回显每个帐户的名称,而不是选择我在 if 语句中选择的帐户。

foreach ($data as $row) {

    $id = $row->id;
    $account = $row->account;
    $time = date("Y-m-d H:i:s");

    if ($id = 100) {echo $account;}
    elseif ($id = 120) {echo $account;}
    else {}

}

Json 就像

{"id":120,"Name":"Companytest"},
{"id":121,"Name":"BensonTillis"},
{"id":123,"Name":"JSBrothers"}

谢谢。

【问题讨论】:

    标签: php json if-statement foreach


    【解决方案1】:

    您需要在 if 语句中使用 == 而不是 =。

    当您比较数字时,您需要使用“==”,因为它是比较运算符之一http://php.net/manual/en/language.operators.comparison.php

    单个“=”是一个赋值运算符,将 $id 设置为右侧的值。 http://php.net/manual/en/language.operators.assignment.php

    【讨论】:

    • 虽然它是正确的(而且问题是重复的),但您应该详细说明为什么需要双重相等而不是单一相等,而不仅仅是“你需要它”。
    • @Qirel OK,编辑了比较和赋值运算符的解释。
    • 谢谢!!!!....newby 错误
    【解决方案2】:

    您应该在“if”条件中使用双等号 == 而不是单号 =

    【讨论】:

      【解决方案3】:

      这是因为您实际上将 $id 分配为 =100

      要解决这个问题,只需在 if 语句中添加第二个 =,如下所示:

      if ($id == 100) {echo $account;}
      

      还有。我已经学会了做我的if 语句,例如:

      if (100 == $id) {echo $account;}
      

      这只会阻止分配变量的可能性,而是会导致:

      语法错误,意外'='

      更容易调试

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-10
        • 2017-07-14
        • 1970-01-01
        • 1970-01-01
        • 2016-06-28
        • 2017-09-27
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多