Add cart values from a Session

Asked

Viewed 241 times

0

How could I print on the screen the total products of a shopping cart coming from a PHP Session?

<?php 
           if(isset($_SESSION['product_cart'])){

           foreach($_SESSION['product_cart'] as $data){
           ?>
        <div class="row">
           <div class="col-xs-2"><img src="images/<?php echo $data['image']; ?>" alt="" style="width:60px;" />
           </div>
           <div class="col-xs-4">
              <h4 class="product-name"><strong><?php echo $data['title']; ?></strong></h4>
              <h4><small>Product description</small></h4>
           </div>
           <div class="col-xs-6">
              <div class="col-xs-6 text-right">
                 <h6><strong><?php echo 
                    number_format((float)$data['price'], 2, '.', ''); 
                     ?> <button class="btn btn-xs btn-danger pull-right" onclick="remove_cart('<?php echo $data['p_id']; ?>')" >x</button></h6>
              </div>
              <div class="col-xs-4">
                 <input type="text" class="form-control input-sm" value="<?php echo $data['quantity']; ?>">
              </div>
              <div class="col-xs-2">
                 <button type="button" class="btn btn-link btn-xs">
                 <span class="glyphicon glyphicon-trash"> </span>
                 </button>
              </div>
           </div>
        </div>
        <hr>
    <?php  }  } ?>

2 answers

2

<?php 
 if(isset($_SESSION['product_cart'])){
  $amount = 0;
  $count = 0;
  $size = count($_SESSION['product_cart']);
 foreach($_SESSION['product_cart'] as $data){
  $count++;
  $amount += $data['price'];
 if($size == $count){
  echo "TOTAL = $amount";
 }
?>
 <div class="row">
 <div class="col-xs-2"><img src="images/<?php echo $data['image']; ?>" alt="" style="width:60px;" />
 </div>
 <div class="col-xs-4">
    <h4 class="product-name"><strong><?php echo $data['title']; ?></strong></h4>
    <h4><small>Product description</small></h4>
 </div>
 <div class="col-xs-6">
    <div class="col-xs-6 text-right">
       <h6><strong><?php echo 
          number_format((float)$data['price'], 2, '.', ''); 
           ?> <button class="btn btn-xs btn-danger pull-right" onclick="remove_cart('<?php echo $data['p_id']; ?>')" >x</button></h6>
    </div>
    <div class="col-xs-4">
       <input type="text" class="form-control input-sm" value="<?php echo $data['quantity']; ?>">
    </div>
    <div class="col-xs-2">
       <button type="button" class="btn btn-link btn-xs">
       <span class="glyphicon glyphicon-trash"> </span>
       </button>
    </div>
 </div>


1


You can use:

$total = array_sum(array_column($_SESSION['product_cart'], 'price'));

echo 'O total é ' . $total;

The array_column() will select only the column price and the array_sum() will add up such values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.