3

When I retrieve the results from a database query in PHP, I receive duplicated values, where ones is an integer, and one has the column name. array_unique(), in sorting the array, would in most cases end up with the numeric key before the string, meaning that would be the key kept. Right now, I use a function that removes from the array anything with a numeric key, but I don't really care for this approach. Does anyone have a better way to do this?

2
  • 4
    SELECT DISTINCT ... in sql would be far more efficient than filtering/de-duping in PHP. prevent the dupes from occuring at all, rather than removing them after the fact. Commented Feb 12, 2013 at 22:16
  • The problem is not that duplicate results are returned from the database, but rather PDO's fetchAll() function returns each item twice, once by index and once by column name. Commented Feb 12, 2013 at 22:43

2 Answers 2

2

Change the command you use to retrieve the values from the database (eg. mysql_fetch_assoc instead of mysql_fetch_array). No matter which api you use now, there is an alternative that does exactly what you want.

update:

In PDO you would write:

$nonumindexes = $res->fetch(PDO::FETCH_ASSOC); 
Sign up to request clarification or add additional context in comments.

3 Comments

Since I'm using PDO, I'm using fetchAll(), so it looks something like $query->fetchAll(). Is there a mysql_fetch_assoc equivalent for PDO? (I'm sorry, I have found the PDO documentation rather difficult to navigate.)
@omniuni or just set the PDO::FETCH_ASSOC as a global attribute, as in here: stackoverflow.com/questions/3893858/…
Thank you! That's much cleaner! I wish it where clearer in the PDO documentation where that option is.
1

I suspect you're using mysqli_fetch_array() to retrieve the results?

If so, the 2nd parameter allows you to retrieves results as an associative array, numeric array or both. Or you can simply use mysqli_fetch_row or mysqli_fetch_assoc to get the results in the format you want.

http://www.php.net/manual/en/mysqli-result.fetch-array.php

Comments

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.