dtu1747 2017-08-25 07:30
浏览 131
已采纳

如何遍历$ _SESSION并从数组中打印值

I have created three files and in one of them i would like to make a loop over a Section to output the name and the price from my array

 <?php
 session_start();
 ?>
<?php 
  $a=array(
      array('id'=>'1','name'=>'Milch','price'=>'12'),
      array('id'=>'2','name'=>'Reis','price'=>'13'),
      array('id'=>'3','name'=> 'Öl', 'price'=>'14'),
      array('id'=>'4','name'=>'Salz','price'=>'15'),
      array('id'=>'5','name'=>'Zucker','price'=>'16'),      
        );       
if(empty($_SESSION['warenkorb'])){       
   echo 'Warenkorb leer';
   }           
else {                          
   foreach($_SESSION['warenkorb'] as $key=>$value){ 
   $_SESSION['warenkorb']=array();            
   print_r($value['name'].': '.'$'.$value['price'].PHP_EOL.'<br />');
     }
   }                                      
  ?>

And this is another file with a lesson that i output from it only the id

<?php
session_start();
?>
 ?php         
     include 'produkte.php';           
     if(!isset($_SESSION['warenkorb'])){  
       $_SESSION['warenkorb']=array();
         }                                
        if(isset($_POST['id'])){             
        foreach($a as $key =>$value){  
        if($value['id']==$_POST['id']){                     
           $_SESSION['warenkorb'][]= $_POST['id'];              
          }              
         }
        }     
        print_r(count($_SESSION['warenkorb']));          
   ?>
  • 写回答

3条回答 默认 最新

  • duan2891 2017-08-25 07:37
    关注

    In first code you need to change some bit in the else part:-

    else {                          
        foreach($_SESSION['warenkorb'] as $key=>$value){  //iterate over SESSION array
            foreach($a as $v){ //iterate over $a array
                if($value == $v['id']){ //compare SESSION is with $a sub-array id         
                    echo $v['name'].': '.'$'.$v['price'].'<br />'; // if match then echo name and price from sub-array
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?