Foreach只返回第一个值

时间:2015-12-29 08:56:05

标签: php foreach

我有一个foreach代码,它应该从数组中获取所有值,我在foreach循环之外调用返回,但即便如此,我仍然只得到第一个值。

以下是我使用的方法:

public function getPriceItem($orderNumber){
  try {
    $query = "SELECT * FROM `orderlist` WHERE `orderNumber` = :orderNumber";
    $stmt = $this->dbh->prepare($query);
    $stmt->bindParam(":orderNumber", $orderNumber);
    $stmt->execute();
    $result = $stmt->fetchAll();

    $i = 0;
    $res = '';
    foreach ($result as $item) {
      $product_arr = explode (",", $item['productName']);
      // $price_arr = explode (",", $item['productPrice']);
      $qty_arr = explode (",", $item['qty']);
        $res .= '<tr><td>'.$product_arr[$i].'(aantal'.$qty_arr[$i].')</td></tr>';
        $i++;
    }
    return $res;
  } catch (Exception $e) {
    $this->error = $e->getMessage();
  }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

你没有遍历你在foreach中创建的产品和数组,你也需要遍历它们:

update
    t1
set
    IsChanged = 1,
    DateModified = isnull((
        select
            max(v)
        from
            (values (t2.DateModified), (t3.DateModified), (t4.DateModified)) as value (v)
    ), '1900-01-01')
from
    Table1 t1
    inner join Table2 t2 on t2.id_Table1 = t1.id_Table1
    inner join Table3 t3 on t3.id_Table2 = t2.id_table2
    inner join Table4 t4 on t4.id_Table3 = t2.id_table3
where
    isnull(t1.DateModified, '1900-01-01') <> isnull((
        select
            max(v)
        from
            (values (t2.DateModified), (t3.DateModified), (t4.DateModified)) as value (v)
    ), '1900-01-01')

我认为不需要$ i

假设您在产品数组和qty数组中拥有尽可能多的值。请提供$ result和您想要的输出的输出!

答案 1 :(得分:0)

我认为您希望所有产品及其数量与订单号相关。然后你需要在foreach循环中再使用一个for循环。使用下面给出的代码修改代码:

public function getPriceItem($orderNumber){
  try {
    $query = "SELECT * FROM `orderlist` WHERE `orderNumber` = :orderNumber";
    $stmt = $this->dbh->prepare($query);
    $stmt->bindParam(":orderNumber", $orderNumber);
    $stmt->execute();
    $result = $stmt->fetchAll();

    $res = '';
    foreach ($result as $item) {
      $product_arr = explode (",", $item['productName']);
      // $price_arr = explode (",", $item['productPrice']);
      $qty_arr = explode (",", $item['qty']);
      for($i=0;$i<count($product_arr) && i< count($qty_arr);i++)
        $res .= '<tr><td>'.$product_arr[$i].'(aantal'.$qty_arr[$i].')</td></tr>';
    }
    return $res;
  } catch (Exception $e) {
    $this->error = $e->getMessage();
  }
}