Question

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...

Was it helpful?

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;

OTHER TIPS

From my understanding of array_unique it does not recursively iterate through an array. It will see that every value of $uu === array() therefore removing all but one of the values whilst preserving the key. I wouldn't be surprised if the key is always 0 as a result.

In the manual see the notes:

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

The DISTINCT keyword acts on the entire row, not just one field. Adding DISTINCT means that each row in the result set will be unique (compared to each other row). It's possible for rows to share some fields, just not all fields.

array_unique() compares items by their string representation. As the manual notes,

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2

String conversion of an array will always yield "Array" so PHP thinks all items are the same and array_unique() only returns one items.

To work around this, you will have to write your own function, probably making sure of in_array(). Since the rows are from the database, you should be able to rework your SQL so only unique rows are returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top