簡體   English   中英

如何在PHP中向數組添加SQL元素

[英]How to add SQL elements to an array in PHP

因此,這個問題可能很基本。

我想從SQL表中的選定元素創建一個數組。

我目前正在使用:

$rcount = mysql_num_rows($result);

for ($j = 0; $j <= $rcount; $j++)
{
    $row = mysql_fetch_row($result);
    $patients = array($row[0] => $row[2]);
}

我想這返回這樣的數組:

$patients = (bob=>1, sam=>2, john=>3, etc...)

不幸的是,以當前形式,此代碼要么不向該數組復制任何內容,要么僅復制最后一個元素。

試試這個吧。

$patients = array();
while ($row = mysql_fetch_row($result)) {
    $patients[$row[0]] = $row[2];
}

如果不起作用,則說明您的查詢出了點問題。

您可以使用print_r()

這是一個例子

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

更多在這里http://php.net/manual/en/function.print-r.php

這個怎么樣 :

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++;
 }   

但是我不確定這是否是您要尋找的,只是猜測.. ount

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM