zack
zack

Reputation: 79

storing results of foreach loop

I have the following php script:

<?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>';
  }


?>

Is there a way to store results of the foreach loop in variables? .i.e $a will contain book name, but if there are two books the value of $a gets overwritten by the next book?

Upvotes: 0

Views: 700

Answers (2)

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

At the core of what you're asking is how to set a key-value pair:

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

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

Because you specify the key $bookName, anything else that has the same name will overwrite the key ($bookName) with the new value ($bookInformation). In php, if you use the construct:

$books[] = $bookInformation;

You will simply append $bookInformation to the end of the $books array.

Note that your code has a number of other issues. $bname is never defined, for instance, and you're mixing output (echo) with business logic (such as saving book names to an array). You should really separate these parts. Also note that you have at least one line that doesn't do anything:

'</br>';

Upvotes: 1

andrewsi
andrewsi

Reputation: 10732

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

You're re-intialising $a in every iteration of the loop.

All you need to do is set it right at the end of the function, with, say, an implode on $output

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

Or, if you don't want the whole output, just use it as an array:

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

Upvotes: 2

Related Questions