【问题标题】:How to convert foreach to if in Php如何在PHP中将foreach转换为if
【发布时间】:2013-07-06 01:52:33
【问题描述】:

我想将 foreach 转换为 if 语句,因为 mysql 查询只返回一行。所以我想使用 if 而不是 foreach

    $db = new db();
    $db -> serverconnection();

    $item = $_GET["name"];

    $query = "SELECT c.firstname,c.phonenumber,c.address FROM `order` o,customerdetails c WHERE o.ordercode = '$item' AND c.sno=o.customerid";

        $results = $db->selectQuery($query);


            foreach ($results as $customerdetails)
            {
                $orderidDetail = $customerdetails['customerid'];
                echo $customerdetails["firstname"];
                echo $customerdetails["phonenumber"];
                echo $customerdetails["address"];       
           }

【问题讨论】:

  • 如果它的目的是什么?

标签: php if-statement for-loop


【解决方案1】:

使用current

$customerdetails = current($results);
if($customerdetails)
    {
    $orderidDetail = $customerdetails['customerid'];
    echo $customerdetails["firstname"];
    echo $customerdetails["phonenumber"];
    echo $customerdetails["address"];       
    }

【讨论】:

    【解决方案2】:

    类似

    if (count($results) == 1) { 
       ... single row of results ...
    } else {
       foreach(...) { ... multiple rows ...}
    }
    

    也许?

    但如果您知道查询只会返回一行,那么无论如何您根本就不需要 if/foreach。

    【讨论】:

      【解决方案3】:

      改变

      foreach ($results as $customerdetails)
      {
          $orderidDetail = $customerdetails['customerid'];
          echo $customerdetails["firstname"];
          echo $customerdetails["phonenumber"];
          echo $customerdetails["address"];       
      

      }

      if(isset($results[0]))
      {
          $orderidDetail = $results[0]['customerid'];
          echo $results[0]["firstname"];
          echo $results[0]["phonenumber"];
          echo $results[0]["address"];       
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-19
        • 2015-03-11
        • 2021-11-28
        相关资源
        最近更新 更多