PDA

View Full Version : Need help breaking out of while() loop - logic problem...


Antivirus
01-07-2008, 08:14 PM
I have the following result set from my db:

-------------------------------
| postid | post_statusid |
-------------------------------
| 100 | 4 |
| 101 | 7 |
-------------------------------

And I am looping through the result set as follows:

$statusid = 8;
while ($post = $vbulletin->db->fetch_array($sql))
{
if ($post['post_statusid'] == 7)
{
$statusid = 7;
}
else if ($post['post_statusid'] == 4)
{
$statusid = 4;
}
else
{
$statusid = 8;
}

// Immediately get out if one of following!
if ($statusid == 7 || $statusid == 4)
{
break;
}
}
echo $statusid;


The rules I want to impose upon the set are as follows:

If any posts have post_statusid of '7' set $statusid = 7
If any posts have post_statusid of '4' and NO posts have post_statusid of '7' set $statusid = 4
If no posts have post_statusid of '7' or of '4' set $statusid = 8

The result set can only have a value of 4,7, or 8. Following are all possible result sets, however the one highlighted in red is giving me a problem. It's returning '4' instead of the needed value of '7':

If: 8,8 $statusid = 8
If: 8,7 $statusid = 7
If: 8,4 $statusid = 4
If: 7,8 $statusid = 7
If: 7,7 $statusid = 7
If: 7,4 $statusid = 7
If: 4,8 $statusid = 4
If: 4,7 $statusid = 7
If: 4,4 $statusid = 4

Anyone have an idea on how to get this one instance of 4,7 to return '7' as I need instead of '4'?

Thanks in advance :)

Opserty
01-07-2008, 08:22 PM
You will be better to store the post_statusid in a temp. array. Then you can make use of in_array() and a few simple if expressions.

$arr = array();
// while($post...
{
// You may want to store postid as key up to you...
$arr[] = intval($post['post_statusid']);
}
// Now we do the checking:
if(in_array(7, $arr))
{
$statusid = 7;
}
elseif(in_array(4 //....
{
$statusid = 4;
}
else
{
$statusid = 8;
}

Makes the logic easier to understand. ;)

Antivirus
01-07-2008, 08:41 PM
perfect, thanks Opserty