简体   繁体   中英

Storing elements in an array at each iteration of a foreach on 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM