Jump to content

[SOLVED] Array matching to display only one record even if multiple matches returned?


cparekh

Recommended Posts

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.

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;

?>            

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.