php mysql查询结果到php数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8970117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:53:21  来源:igfitidea点击:

mysql query result into php array

phpmysqlarrays

提问by fish man

Some code here, I want store mysql query result into an array with php, but my code return result: 2h, not what I wish.(the correct result should be 36,35,34,33,32)

这里的一些代码,我想用php将mysql查询结果存储到一个数组中,但我的代码返回结果:2h,不是我想要的。(正确的结果应该是36,35,34,33,32)

<?php
set_time_limit(59);
mysql_select_db("mycoon",$db);
mysql_query("SET NAMES utf8"); 
$result = mysql_query("SELECT id,link FROM mytable Order By id DESC LIMIT 0,5");
$new_array[] = $row;
while ($row = mysql_fetch_array($result)) {
    $new_array[$row['id']] = $row;
    $new_array[$row['link']] = $row;
}
mysql_close($db);// close mysql then do other job with set_time_limit(59)
foreach($new_array as $array){
    echo $array['id'].'<br />';
    echo $array['link'].'<br />';
}
?>

Result:

结果:

36
http://localhost/img/img36.jpg
36
http://localhost/img/img36.jpg
35
http://localhost/img/img35.jpg
35
http://localhost/img/img35.jpg
34
http://localhost/img/img34.jpg
34
http://localhost/img/img34.jpg
33
http://localhost/img/img33.jpg
33
http://localhost/img/img33.jpg
32
http://localhost/img/img32.jpg
32
http://localhost/img/img32.jpg

回答by Vyktor

I think you wanted to do this:

我想你想这样做:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

或者也可以将 id 存储为密钥

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

使用您将能够直接被其ID地址行,如第二种方式:$new_array[ 5]

回答by makriria

Use mysql_fetch_assoc instead of mysql_fetch_array

使用 mysql_fetch_assoc 而不是 mysql_fetch_array

http://php.net/manual/en/function.mysql-fetch-assoc.php

http://php.net/manual/en/function.mysql-fetch-assoc.php

回答by Zulkhaery Basrul

What about this:

那这个呢:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

要检索链接和 ID:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}