How do I stop MySQL from duplicating every column's entry in returned arrays?

这一生的挚爱 提交于 2020-01-11 12:22:48

问题


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 if 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?


回答1:


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.




回答2:


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)




回答3:


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);



回答4:


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.



来源:https://stackoverflow.com/questions/3711133/how-do-i-stop-mysql-from-duplicating-every-columns-entry-in-returned-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!