Comparing two sets

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Comparing two sets

Post by GeXus »

I posted a similar problem in the database thread, but this is different and I think it's more of a PHP thing... I have two tables,

1. Groups
- country_codes

2. Sets
- country_codes


The country codes are comma delimited (i.e, US,UK,CA would be a record set). I want to find which ones have intersecting country_codes. So, if I select country_codes from "Groups" and it returns UK,US,CA - I want to then get all "Sets" that have country_codes values of any of the three. So if a record has AU,FI,US, it would return...

So, I'm thinking of just selecting the set I want, then selecting all groups and using array_intersect(), however I can't seem to figure out how to maintain the associated array. I've tried array_intersect_assoc, but then It's comparing against the whole associated array (which includes ID, Name and country_codes), not just the country_codes.

Anyone have any ideas? Or did I just confuse the hell of you..... :)
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Comparing two sets

Post by Benjamin »

Are they stored in a blob or something? They are stored comma delimited?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Comparing two sets

Post by Benjamin »

Just typed this to give you a rough idea of how I would do it.

Code: Select all

 
$search_for = explode(',', 'UK,US,CA');
 
$sets = array();
$db->query("select id, data from sets");
 
while ($x = $db->get_row())
{
    $sets[$x['id']] = array_map('trim', explode(',', $x));
}
 
$results = array();
 
foreach ($sets as $id => $codes)
{
    if (in_array($search_for, $codes))
    {
        $results[] = $id;
    }
}
 
# results contains record id's of matching sets..
 
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Comparing two sets

Post by Christopher »

Or:

Code: Select all

$country_codes = 'UK,US,CA';   // value from Groups
$codes= explode(',', $country_codes);
 
$where = "country_codes LIKE '%" . implode("%' OR country_codes LIKE '%", $codes) . "%'";
$db->query("SELECT * FROM Sets WHERE $where");
 
while ($x = $db->get_row())
{
# results contains record id's of matching sets..
}
(#10850)
Post Reply