如何在PHP中将SQL元素添加到数组中

如何在PHP中将SQL元素添加到数组中,php,mysql,arrays,Php,Mysql,Arrays,所以这个问题可能很基本 我想从SQL表中的选定元素创建一个数组 我目前正在使用: $rcount = mysql_num_rows($result); for ($j = 0; $j <= $rcount; $j++) { $row = mysql_fetch_row($result); $patients = array($row[0] => $row[2]); } <pre> <?php $a = array ('a' => 'appl

所以这个问题可能很基本

我想从SQL表中的选定元素创建一个数组

我目前正在使用:

$rcount = mysql_num_rows($result);

for ($j = 0; $j <= $rcount; $j++)
{
    $row = mysql_fetch_row($result);
    $patients = array($row[0] => $row[2]);
}
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
不幸的是,在其当前形式中,此代码要么不向数组复制任何内容,要么只复制最后一个元素。

您可以使用
print\r()

这里有一个例子


更多信息请点击这里

while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $count=0;
        while ($count < mysql_num_fields($result)) {       
            $col = mysql_fetch_field($result, $count);   
            $arr_row[$col -> $count] = $row[$col -> $count];           
            $count++;
 }   
如果它不起作用,说明您的查询有问题。

这个怎么样:

while($row=mysql\u fetch\u assoc($result)){
$arr_row=array();
$count=0;
而($count$count]=$row[$col->$count];
$count++;
}   

但是我不确定这是否是您要寻找的,只是猜测..ount

我真的不明白您想在这里做什么,在for循环中,您没有使用变量j。请说得更清楚,我不确定我是否明白,这不就是在我创建数组后打印数组的元素吗。此外,据我所知,这不允许我仅从表中选择要放入数组的某些元素。这与我想要的更接近,但我正在尝试避免在数组中包含数组。是否有某种方法可以修改此设置,使我没有数组([0]=>array([bob]=>5)[1]=>array([fred]=>1)),而是数组([bob]=>5[fred]=>1)?谢谢。
$patients = array();
while ($row = mysql_fetch_row($result)) {
    $patients[$row[0]] = $row[2];
}
while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $count=0;
        while ($count < mysql_num_fields($result)) {       
            $col = mysql_fetch_field($result, $count);   
            $arr_row[$col -> $count] = $row[$col -> $count];           
            $count++;
 }