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 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题