问题
I am getting strange behaviour from this function.
Input
public function fetch_array($result_set)
{
$rows = array();
while ($row = mysql_fetch_array($result_set))
{
$rows[] = $row;
print_r($row);
break;
}
return $rows;
}
I have made the function run once but it its duplicating a row from my MySQL query result.
Output
Array ( [0] => Sarah [first_name] => Sarah [1] => Palin [second_name] => Palin )
It should be
Correct Output
Array ( [first_name] => Sarah [second_name] => Palin )
I used this SO question example
Use mysql_fetch_array() with foreach() instead of while()
Not my query or Mysql result fault
http://i.imgur.com/CZnIF.png

What is going wrong here?
回答1:
This is not an error, it's the intended behavior of mysql_fetch_array()
http://us.php.net/manual/en/function.mysql-fetch-array.php
You can either set the result_type
flag, or you can just use mysql_fetch_assoc()
instead. http://us.php.net/manual/en/function.mysql-fetch-assoc.php
回答2:
When using mysql_fetch_array, feed it the MYSQL_ASSOC flag.
EDIT: Here's your code, with the appropriate change
while ($row = mysql_fetch_array($result_set, MYSQL_ASSOC))
Also, you can get them with just the numeric indices by feeding it MYSQL_NUM
回答3:
The reason why you get one result and wanting the other is because you are pushing an array($row) inside a new array ($rows). By pushing something in an array(The brackets you use) you get an auto incrementing key with it.
回答4:
try this:
$rows['name'] = $row['name'];
$rows['second_name] = $row['second_name'];
...
instead of
$rows[] = $row;
回答5:
By default mysql_fetch_array
has two keys for each database column -- one with the numerical key and one with the associative key.
You can do this to tell it only to fetch the numeric keys:
mysql_fetch_array($result, MYSQL_NUM);
http://us2.php.net/manual/en/function.mysql-fetch-array.php
回答6:
It is completely normal and expected behaviour. If you just want the associative array, use
while ($row = mysql_fetch_array($result_set, MYSQL_ASSOC))
来源:https://stackoverflow.com/questions/12921939/fetch-array-function-doubling-values-in-each-position-of-array