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 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段