Jump to content

A problem with a loop


SyLon

Recommended Posts

hi  :)

This code should return me an array with posts IDs who match the $tag (array), so here what I did:

 

foreach($tag as $k=>$v) { 
            while( $row=mysql_fetch_assoc($query))
            {
                show($row['id'].$v);
                $post_tags=return_tags_by_id($row['id']);
                if( in_array($v,$post_tags) && !in_array($row['id'],$matching_posts) ) {
                    $matching_posts[]=$row['id'];
                }

            } # while
        } # foreach

After some testing I figured out that the while loop is getting looped only once - only at the first time, while the foreach loop is fine.

it seems like $row != mysql_fetch_assoc($query) after the first loop, so I tried to unset($row) at the beginning of each foreach loop but it doesn't work.

I'm pretty sure that there is something wrong with my while loop, but what??

Hope you can help, Thanks!

Link to comment
Share on other sites

Problem solved!

I put the query inside the foreach loop, like that: (It's a function and $query is a parameter)

 

 foreach($tag as $k=>$v) { 
            $query2=mysql_query($query);
            while( $row=mysql_fetch_assoc($query2))
            {
                
                $post_tags=return_tags_by_id($row['id']);
                if( in_array($v,$post_tags) && !in_array($row['id'],$matching_posts) ) {
                    $matching_posts[]=$row['id'];
                }
                
            } # while
        } # foreach

Thanks for helping guys!

ohh, by the way, whats the difference between mysql_fetch_assoc() and mysql_fetch_array() ?

Link to comment
Share on other sites

mysql_fetch_assoc gets the result row as an associative array, mysql_fetch_array gets it as an associative array, a numerica rray, or both, so basically, with mysql_fetch_assoc, you can only call up the values like this:

 

$row['id'];

 

with mysql_fetch_array, you can call them up like this:

 

$row['id'];

 

or this:

 

$row[1];

 

calling mysql_fetch_assoc() is the same as this:

 

mysql_fetch_array($result, MYSQL_ASSOC);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.