My MySQL queries are returning arrays with duplicate entries: numbered keys and labeled keys with the same data inside. This may be standard, but it seems like a waste, and something that could cause problems i开发者_开发技巧f I'm printing values. I mean, not a huge problem, obviously. But I'm just curious if I can stop that. It seems unnecessary. For example:
Array(
[0] => "Ted",
[first_name] => "Ted",
[1] => "Schmidlap",
[last_name] => "Schmidlap"
)
And so on.
I'm pretty new to a lot of this, so this may be a simple question, but Googling doesn't seem to have any answers for me. Anyone know the reason this happens? I'm using PHP's PDO now, but I was doing it straight through the MySQL functions before and the same thing was happening, so I assume it's a byproduct of MySQL interaction.
I can iterate through and unset the numeric ones, because I don't need them, but they're not really in the way right now, so that's just an extra step. Still, is there a way to simply not have them fetched in the first place?
Presumably this is happening after you use mysql_fetch_array
(or similar).
You need to add in a flag to specify what array type you want returned or PHP assumes both.
i.e. mysql_fetch_array($result_set, MYSQL_ASSOC|MYSQL_NUM|MYSQL_BOTH)
That depends on the function you are using. Some functions return both types, others return only one of them.
If you are using PDOStatement->fetch
, notice the optional $fetch_style argument it takes.
Your issue is with the mysql_fetch_array
function.
If you want only the numbers, use:
$row = mysql_fetch_array($result, MYSQL_NUM)
If you want only the text indexes, use:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
I usually use MySQLi but for PDO you can find more information here: http://us3.php.net/manual/en/pdostatement.fetch.php
Which seems to mean that you should be using this for text indexes:
$row = $statement->fetch(PDO::FETCH_ASSOC);
And this for numeric indexes:
$row = $statement->fetch(PDO::FETCH_NUM);
Also, just to note this since it isn't listed here, if you want an associative array, you can use mysql_fetch_assoc(), or if you want an enumerated (numbered) array use mysql_fetch_row() instead of mysql_fetch_array(). I use this mostly because without it I would often forget the flag, so I got into the habit of just using the specific function.
精彩评论