Adding cart values from a session

0

How can I print on the screen the total of the products in 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  }  } ?>
    
asked by anonymous 06.09.2017 / 19:55

2 answers

1

You can use:

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

echo 'O total é ' . $total;

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

    
26.09.2017 / 22:29
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>

  
06.09.2017 / 20:09