问题
I am trying to convert a php resultset into an array (using foreach), I'm not quite doing it right..
I have a resultset:
$result
I am looping through it as below: (horribly wrong)
while($row = mysql_fetch_array($result)) {
foreach (mysql_fetch_array($result) as $k => $v) {
echo "Fred's $k is ". $v['uid']. "\n";
}
}
I want this array to be in the below format:
Array
(
[0] => Array //row1
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[1] => Array //row2
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[2] => Array //row3
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
)
I am a newbie, please help.
回答1:
$results = array();
while($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}
//$results has all that you need
print_r($results);
回答2:
You don't need a foreach to do this, you can just stick with your while loop:
$result_set = array();
while($row = mysql_fetch_array($result)) {
$result_set[] = $row;
}
Then you can use it like a normal array:
$result_set[0]['column_name'];
回答3:
i can't understand well but hope this will help you :
$array = array();
while($row = mysql_fetch_array($result)) {
$array[] = $row['uid'];
}
回答4:
Try this,
while($row = mysql_fetch_assoc($result)) {
$ar[]=$row;
}
回答5:
Try mysql_fetch_assoc instead:
$results_array = array();
while($row = mysql_fetch_assoc($result)) {
$results_array[] = $row;
}
来源:https://stackoverflow.com/questions/8515191/convert-a-php-resultset-into-an-array