0

How could I build a unique array check each of the address fields.

E.g at the moment I get everything:

$stmnt = "SELECT `location_id`, `location_address1`, `location_address2`,
            `location_town`, `location_region`, `location_postcode`
          FROM locations WHERE user_id = '{$id}'";
$results = $db->fetchAll($stmnt);

    if(!empty($results ))  {
        foreach($results as $row) {
            if($unique){
                $value = $row['location_id'];
                $label = implode(", ", array(
                    'address1'      => $row['location_address1'],
                    'address2'      => $row['location_address2'],
                    'town'          => $row['location_town'],
                    'region'        => $row['location_region'],
                    'postcode'      => $row['location_postcode']
                ));
            }

I was thinking that where if($unique){ is you would check this address1, address2, etc exist in the temp array by searching this some how?

7
  • 2
    Why not just do a SELECT DISTINCT ...? Commented Sep 27, 2012 at 19:38
  • do u want unique rows, or unique values inside each row? Commented Sep 27, 2012 at 19:42
  • That may work, but that returns the distinct {location_id, location_address1, ... location_postcode} pairs. I'm not 100% sure if that's what OP wants or if they want all the distinct location_id, all the distinct location_address1, etc. Commented Sep 27, 2012 at 19:42
  • 1
    you could use !in_array($uniqueColumn, $tmpArray) and push your unique column in $tmpArray ( php.net/manual/en/function.in-array.php ) . Commented Sep 27, 2012 at 19:43
  • When I add a DISTINCT this doesn't make any difference and always returns the same amount of rows. I am guessing because of the primary key location_id Commented Sep 27, 2012 at 19:55

1 Answer 1

2

Using SELECT DISTINCT will allow you to bring back a unique set of results, excluding results that are dupliciates of another. You can even still use the ORDER BY if you intend to, but remember that with a DISTINCT selection, anything in the ORDER BY must also be in the SELECT statement.

2
  • Is this affected by the primary key and other fields I have in the row? I didn't show them because I didm't think it would be relevant Commented Sep 27, 2012 at 20:01
  • yes, having a unique column in the select statement would defeat the point of the DISTINCT keyword. Some database types might behave differently however, I would ommit the ID if you dont need it. Commented Sep 27, 2012 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.