cparekh Posted February 2, 2009 Share Posted February 2, 2009 Hi, I'm trying to compare two arrays to qualify records from a dataset to display and although the comparison work fine I end up displaying the same record multiple each time the array comparison is true. To explain better here is the scenario: I have one table of articles and another table of user-profiles. I'm trying to show a user articles based on their profile setting so for example I'm using geographic location of the user where their location is held in the 'locations' column as a string e.g. '1,2' where 1 and 2 relate to different locations. Likewise in the user profile I have a location column to specify what locations they'd like to be able to view articles for. I'm pulling each of these out as an array and comparing them for a match but only want to display a record once, even if it matches multiple times. How do I break out of the loop and more importantly which loop do I break out of? Here's the code: <?php $k = 0; foreach($article_rows as $article_row) { //get the location info for each article $locations_a = explode(',', $article_row->locations); //for each location id for an article, compare against profile $i=0; foreach ($locations_a as $a) //from article { $j=0; foreach ($locations_p as $p) //from profile { if($a == $p) { ?> <li ><?php echo $article_row->title; ?></li> <?php } $j++; } $i++; } $k++; ?> Any help or guidance is greatly appreciated. Thanks, C. Quote Link to comment Share on other sites More sharing options...
Snart Posted February 2, 2009 Share Posted February 2, 2009 Stick them in an array and check if they already exist in that array. That way, you can also sort the array afterwards if you wish, and you can concatenate the results into one big string before echoing (one big echo is faster than multiple small ones). Untested code, so may still contain errors: <?php $articlesToShow = array(); $k = 0; foreach($article_rows as $article_row) { //get the location info for each article $locations_a = explode(',', $article_row->locations); //for each location id for an article, compare against profile $i=0; foreach ($locations_a as $a) //from article { $j=0; foreach ($locations_p as $p) //from profile { if(($a == $p) && (!in_array($article_row->title, $articlesToShow))) { $articlesToShow[] = $article_row->title; } $j++; } $i++; } $k++; $arts = ''; foreach($articlesToShow as $art) { $arts .= '<li>'.$art.'</li>' } echo $arts; ?> Quote Link to comment Share on other sites More sharing options...
cparekh Posted February 3, 2009 Author Share Posted February 3, 2009 Yep, that works great! I changed it a tad to suit my needs but that did it. Thanks very much, C. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.