Iterating FOREACH arrays in a FOR loop
I've been trying to learn PHP for the past week and I'm stuck at a particular problem. Please excuse my poorly worded title as I haven't grasped the jargon yet.
Here's my code:
$query = "SELECT $tablefields FROM $tablename";
$sth = $dbconn->prepare($query);
for ($x = 1; $x <=3; $x++){
echo '<br /> This is an iteration ',$x;
$sth->execute();
foreach ($sth->fetchall() as $row)
{
$results = $row[$tablefields];
echo $results, '<br />'
;
}
}
I want the code to output as below:
This is iteration No. 1
Apple
Orange
Banana
Kiwi
This is iteration No. 2
Apple
Orange
Banana
Kiwi
This is iteration No. 3
Apple
Orange
Banana
Kiwi
Now, the above code does the job just fine but when I want to increase the iterations $x<=20, and the fruit options to 20 items, there's a noticeable slowdown in the page rendering. I was wondering whether it's because the code is querying the MySQL database 20 times? Is there a better way to structure the code so that it's more efficient?
Because you do MySQL query 20 times. You can cache the result and then loop using the cache. For example:
$query = "SELECT $tablefields FROM $tablename";
$sth = $dbconn->prepare($query);
$sth->execute();
$result = "";
foreach ($sth->fetchall() as $row) {
$result .= $row[$tablefields] . "<br>";
}
for ($x = 1; $x <=3; $x++){
echo '<br /> This is an iteration ' . $x;
echo $result;
}
$x=1;
foreach ($sth->fetchall() as $row){
echo '<br /> This is an iteration ',$x;
$results = $row[$tablefields];
echo $results;
$x++;
}
您可以使用上面的代码,而不是一起使用for循环和foreach。
Here is the thing..
I don't why you are executing query thrice or each time loop is running. But here is the little improvement over your code. Take a look.
$query = "SELECT $tablefields FROM $tablename";
$sth = $dbconn->prepare($query);
$sth->execute();
$data = "";
foreach ($sth->fetchall() as $row) {
$data .= $row[$tablefields] . "<br>";
}
for ($x = 1; $x <=3; $x++){
echo '<br /> This is an iteration ' . $x;
echo $data;
}
链接地址: http://www.djcxy.com/p/59076.html
上一篇: PHP脚本不传递数组变量的URL
下一篇: 在FOR循环中迭代FOREACH数组