在PHP上的foreach的每次迭代中将元素存储在数组中 [英] Storing elements in an array at each iteration of a foreach on PHP
问题描述
我有一个foreach来检查我的php站点中的会话数,并检查它从数据库中获取项目名称的每个会话。
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.
这里是foreach:
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);
}
假设有3个会话,我如何继续保存$ row2 ['名称]以后可以使用的其他变量中?
Let's say there are 3 sessions, how could I keep saving $row2['name'] in different variables that I could use later?
谢谢!
推荐答案
在 foreach
之前定义一个数组,用于将结果存储在以下位置:
Before the foreach
define an array to store results in:
$mySessions = array();
然后在 $ row2 = ...之后。 c>行:
Then after the $row2 = ....
line:
$mySessions[] = $row2;
然后,您将填充数组,以便在循环完成后可以使用它。
Then you will have the array populated so you can use it after your loop is completed.
这篇关于在PHP上的foreach的每次迭代中将元素存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!