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 Answers
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);
3 Comments
omniuni
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.)fdreger
@omniuni or just set the PDO::FETCH_ASSOC as a global attribute, as in here: stackoverflow.com/questions/3893858/…
omniuni
Thank you! That's much cleaner! I wish it where clearer in the PDO documentation where that option is.
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.
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.