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

在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!

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.