Jump to content

an Explode and ForEach problem.


andyhajime

Recommended Posts

I can't seem to find the logic of doing this. I hope you guys out there help me out on my problem.

This is what I did so far.

 

$selected_user = "3, "; 

$sql = "SELECT * FROM userdata WHERE user_active = 'yes'";
if(!$result = $db->sql_query($sql)){ echo 'error'; exit; }

while ($row = $db->sql_fetchrow($result))
{
$user_id = $row['user_id'];

$selected_user = explode(", ", $selected_user);

  foreach ($selected_user as $SELECT_ID)
  {
        if($user_id == $SELECT_ID)
        {
        echo 'userid is ' .$user_id . '[ ENABLED ]' . '<br>';
        }else{
        echo 'userid is ' .$user_id . '[ DISABLED ]' . '<br>';
        }
    }
}

 

The result i got was this, which is wrong:

userid is 1 [ DISABLED ]

userid is 1 [ DISABLED ]

userid is 2 [ DISABLED ]

userid is 2 [ DISABLED ]

userid is 3 [ ENABLED ]

userid is 3 [ DISABLED ]

userid is 4 [ DISABLED ]

userid is 4 [ DISABLED ]

 

Notice the "userid is 3"?

It was ENABLED at first but it somewhat 're-looped' again and make it "DISABLED" instead.

 

I'm trying to get this result

userid is 1 [ DISABLED ]

userid is 2 [ DISABLED ]

userid is 3 [ ENABLED ]

userid is 4 [ DISABLED ]

 

 

Can anyone tell me where I did wrong?

Link to comment
https://forums.phpfreaks.com/topic/98839-an-explode-and-foreach-problem/
Share on other sites

This could possibly be owing to the syntax of the method.

 

while ($row = $db->sql_fetchrow($result))

 

As I recall the syntax, sql_fetchrow is probably returning a number AND the name of the columns selected.

E.g.

$row['user_id'] and $row[0] are the same values which is why it loops twice.

 

for a quick fix, maybe, change the syntax of the query method to one that returns only the name of the number instead of both

or

add another loop which involves an incrementing number and call the values as $row[$i]. but that gets a little confusing

as for the first option, if it's a custom made method, alter the code to only retrieve the numbers or names of the selected columns.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.