存储 foreach 循环的结果


storing results of foreach loop

我有以下php脚本:

<?php
  session_start();
  global $db;
  $cart = $_SESSION['cart'];
  if ($cart) {
    $items = explode(',',$cart);
    $contents = array();
    foreach ($items as $item) {
      $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
    }
    $output[] = '<form action="cart.php?action=update" method="post" id="cart">';
    $total=0;
    echo 'you have following books';
    echo '</br>';
    $output[] = '<table>';
    foreach ($contents as $id=>$qty) {
      $sql = "SELECT * FROM books WHERE bcode ='$id'";
      $result = $db->query($sql);
      $row = $result->fetch();
      extract($row);
      $output[] = '<tr>';
      $a = $output[] = '<td>  '.$bname.'</td>';
      $output[] = '<td>'.$price.'rs.</td>';
      $output[] = '<td>*'.$qty.'</td>';
      '</br>';
      $output[] = '<td>Rs.'.($price * $qty).'</td>';
      $total += $price * $qty;
      $output[] = '</tr>';
    }
    $output[] = '</table>';
    $output[] = '<p>Grand total: <strong>Rs.'.$total.'</strong></p>';
    $output[] = '</form>';
  } else {
    $output[] = '<p>You shopping cart is empty.</p>';
  }

?>

有没有办法将foreach循环的结果存储在变量中?即$a将包含书名,但如果有两本书,$a的值会被下一本书覆盖?

$a= $output[] = '<td>  '.$bname.'</td>';

您在循环的每次迭代中重新初始化$a

您需要做的就是在函数的末尾设置它,例如,内爆$output

$a = implode (''n', $output);

或者,如果您不想要整个输出,只需将其用作数组:

$a[] = $output[] = '<td>  '.$bname.'</td>';

您询问的核心是如何设置键值对:

$books = array();
foreach ($items as $item) {
  //get $bookName and $bookInformation
  //Save
  $books[$bookName] = $bookInformation;
}

因为您指定了键$bookName,所以任何其他具有相同名称的内容都将用新值($bookInformation)覆盖键($bookName)。在 php 中,如果您使用构造:

$books[] = $bookInformation;

您只需将$bookInformation追加到$books数组的末尾。

请注意,您的代码还有许多其他问题。 例如,$bname从未定义过,并且您正在将输出(echo)与业务逻辑(例如将书籍名称保存到数组)混合在一起。你真的应该把这些部分分开。另请注意,您至少有一行不执行任何操作:

'</br>';