Jump to content

Recommended Posts

Posted

Hi all,

Before you ask, this is part of my learning process so am not busy breaking somebody's site :):P

OK, I am now comfortable enough using foreach loops in PW. I am now onto "while loops".

How can I replicate the following "while loop" code in PW? I've learnt that it is common to use similar code to access tables in a database. While there are still results, keep on getting them and add them to an array...

$rows = array();
$results = $db->query("SELECT id, name, data FROM some_table"); 
while($row = $results->fetch_array())
{
	$rows[] = $row;
}
	

Now, in my case, my data is in PW as normal PW pages. I do not need to do the $db->query thing. I can use PW selectors. The $results bit is straightforward, .e.g using $pages->find('something'); I also know $pages->find(); will return an array (PageArray).

Where am getting stumped is how to use the while loop to do the same thing the above code is doing but using PW API. Specifically, what I don't get is how to replicate the $results->fetch_array() bit using PW API. 

I have Googled the forum and haven't found anything but examples of querying external tables as shown above. I have also checked the API documentation but nothing has worked for me yet. I am either getting endless loops (white screen) or no items get added to the array :).

Here's my question in code. I know the $results->fetch_array() will not work here :):-[

$rows = array();
$results = $pages->find('template=basic-home, limit=20'); 
while($row = $results->fetch_array())//how to replicate this fetch_array bit?
{
	$rows[] = $row;
} 

Or, should I not use the while loop in such a case? Use something else? Thanks!

Posted
while(youcan < youshould) {
    // do what you want
} 

:D Well use foreach... It's just a matter of preference and you could even use for() foreach() while()

A while loop with a PageArray would look like this:

$res = $pages->find("template=somexy, limit=10");
$i = 0;
while($r = $res->eq($i)){
    echo $r->title . "<br/>";
    $i++;
}
  • Like 2
Posted

Hi kongondo,

There's no reason to use a while loop in the situation where you are just iterating over the pages found.

Generally: If you need to loop over a set of data, you're free to choose the type of loop (for, while, do-while).

However, it depends on the situation which one you take :)

As for your example, you could do it in a while loop like this:

$i = 0;
while (count($results)) {
  $p = $results->get($i);
  $rows[] = $p;
  $results->remove($i);
  $i++;
}
  • Like 3

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...