dswy34539 2013-04-09 20:00
浏览 36
已采纳

在PHP的foreach的每次迭代中存储数组中的元素

I have a foreach that checks the number of sessions in my php site and for each session it fetches from a db the name of an item.

I would like to store the names sequentially in variables so I could use them after, so I don't have to make a second call to the database.

Here is the foreach:

foreach ($_SESSION['cart'] as $item) 
{ 
    $pid = $item['itemId'];
    $q = $item['qty'];
    $query2 = $con -> prepare("SELECT * FROM item_descr WHERE id_item = :idItem");
    $query2-> bindValue (':idItem',$pid);
    $query2->execute();
    $row2 = $query2->fetch(PDO::FETCH_ASSOC);
}

Let's say there are 3 sessions, how could I keep saving $row2['name'] in different variables that I could use later?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongliang2058 2013-04-09 20:02
    关注

    Before the foreach define an array to store results in:

    $mySessions = array();
    

    Then after the $row2 = .... line:

    $mySessions[] = $row2;
    

    Then you will have the array populated so you can use it after your loop is completed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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