简体   繁体   中英

Multidimensional session array printing the elements by using echo function

I have piece of code that I need to use echo function in order to print the variables inside the session array, on the other hand I need to add prices one by one every time user chooses a product. The prices variable is a string. The code as follows:

    if (!is_array($_SESSION['products']['names'])){

      $_SESSION['products']['names']['name'] = array();
      $_SESSION['products']['names']['prices']= array();

      }else {

     $pros = $_SESSION['products']['names']['name'];

     if (in_array($product->getName(), $pros, true)){

         echo 'The product is available in your basket';

} else {

 $prozuct = array_push($_SESSION['products']['names']['name'],$product->getName());
                          array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));

     foreach ($_SESSION['products'] as  $id=>$arr){

     for ($i=0;$i<count($arr);$i++){

      echo $arr['name'][$i];

       }                             
  }

 }   
}

The error that I receive is:

Notice: Undefined offset: 1 in /Users

And additionally I know that I can use print_r but in my case I want to add prices one by one and calculate and show the total of amount to user.

No need for a loop:

$namesHtml = implode("<br>", $_SESSION['products']['names']['name']);
$total = array_sum($_SESSION['products']['names']['price']);
echo sprintf("<p>Products: <br>%s<br>Total Cost: %s", $namesHtml, $total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM