存储foreach循环的结果

时间:2012-08-14 18:33:08

标签: php foreach

我有以下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循环的结果? .i.e $ a将包含书名,但是如果有两本书,$ a的值会被下一本书覆盖?

2 个答案:

答案 0 :(得分:2)

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

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

您需要做的只是在功能结束时设置它,例如,$output

上的内爆
$a = implode ('\n', $output);

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

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

答案 1 :(得分:1)

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

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

  //Save
  $books[$bookName] = $bookInformation;
}

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

$books[] = $bookInformation;

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

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

'</br>';