Search code examples
phparray-unique

array_unique only returns one record


In the code below:

$sth = $dbh->query('SELECT DISTINCT title,courseId,location from training');  
$sth->setFetchMode(PDO::FETCH_ASSOC); 
$results = $sth->fetchAll();
$uu = array_unique($results);

echo "<pre>";
print_r($uu);
echo "</pre>";

I only get 1 results from print_r($uu);

If I remove array_unique All (30+) rows are returned. (No, not all of them are duplicates) :)

What am I doing wrong?

EDIT var_dump() results:

array(23) {
  [0]=>
  array(3) {
    ["title"]=>
    string(26) "String Here"
    ["courseId"]=>
    string(1) "8"
    ["location"]=>
    string(1) "1"
  }
  [1]=>
  array(3) {
    ["title"]=>
    string(26) "Another String Here"
    ["courseId"]=>
    string(1) "8"
    ["location"]=>
    string(1) "2"
  }
  [2]=>
  array(3) {
    ["title"]=>
    string(24) "Third String Here"
    ["courseId"]=>
    string(1) "5"
    ["location"]=>
    string(1) "2"
  }

etc...


Solution

  • From the manual:

    Note: Note that array_unique() is not intended to work on multi dimensional arrays.

    Further:

    Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

    When an array is cast to a string you get "Array".


    Why are you calling array_unique anyway? Your database already ensured uniqueness.

    I'm not exactly sure on the details but this seems to be what you want. Still learning SQL myself.

    SELECT title, courseId, location
    FROM training
    GROUP BY title;