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条)

报告相同问题?

悬赏问题

  • ¥30 求一下解题思路,完全不懂。
  • ¥30 关于#硬件工程#的问题:求一下解题思路
  • ¥15 运筹学对偶单纯行法构造扩充问题
  • ¥20 XP系统的老电脑一开机就提示找不到rundll.exe,付费求解
  • ¥15 milvus查询出来的score怎么转换成0-1之间的相似性
  • ¥15 多ip服务器站群如何搭建l2tp服务器
  • ¥15 lvgl V9移植到linux开发板
  • ¥15 VB.net中在窗体中创建一个button控件来关闭窗体,但是提示错误,我该怎么办
  • ¥15 网上下载好的程序但是arduinoIDE编程报错,运行不了,哪里出错了,能具体给改一下吗
  • ¥15 Sharepoint JS开发 付费技术指导