mysql查询结果到php数组 [英] mysql query result into php array

查看:44
本文介绍了mysql查询结果到php数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
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 />';
}
?>

结果:

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

推荐答案

我认为你想这样做:

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

或者也可以将 id 存储为键

Or maybe store id as key too

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

使用第二种方式,您可以直接按行的 ID 寻址,例如:$new_array[5].

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

这篇关于mysql查询结果到php数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆