Reputation: 47
I need to iterate through data pulled from an mssql database twice in my php, but I find that when I perform the first foreach loop the array is then listed as empty as the array pointer has moved through the entire array.
In essence I have this:
$rstGold = $rstGold2 = getFeatured();
foreach($rstGold as $store){
//proccessing here
}
foreach($rstGold2 as $store){
//proccessing here
}
get featured is a sql query returning results using the mssql-PDO driver.
function getFeatured(){
global $db, $debug;
$query = //sql query
return $db->query($query);
}
I need a way to iterate through the results of getFeatured() twice, with them remaining in the same order. My sql query randomizes the results so I cannot perform a second sql query.
While writing this I found a way to perform all of the processing in the same loop, but would still like to know what the best way to do this would be.
Upvotes: 0
Views: 246
Reputation: 34657
Use an ArrayIterator, per the docs:
When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually.
And the example follows:
<?php
$fruits = array(
"apple" => "yummy",
"orange" => "ah ya, nice",
"grape" => "wow, I love it!",
"plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();
// How many items are we iterating over?
echo "Iterating over: " . $obj->count() . " values\n";
// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
echo $it->key() . "=" . $it->current() . "\n";
$it->next();
}
// The good thing here is that it can be iterated with foreach loop
foreach ($it as $key=>$val)
echo $key.":".$val."\n";
The class also has a method to reset the pointer to the beginning called rewind
, used as follows:
$iterator = $arrayobject->getIterator();
$iterator->next();
echo $iterator->key(); //1
$iterator->rewind(); //rewinding to the begining
Hope that helps.
Upvotes: 2