如何使用php将while循环结果存储到数组中

时间:2015-01-13 07:39:02

标签: php

我有一个mysql查询,它返回来自db的匹配数据。我需要将匹配的结果数据存储到$autocompletiondata,如下所示:

$autocompletiondata =  array(
        1 => "shibbir",
        2 => "ahmed",
        3 => "babu",
        4 => "rahim",
        5 => "shakil",
);

Sql查询:

$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata =  array(
        $cdid => "$fname");
}

如何将所有匹配数据存储到关联数组? Plz的帮助。

5 个答案:

答案 0 :(得分:3)

你能试试吗?

$autocompletiondata = array();

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] =  $fname;
}

答案 1 :(得分:0)

while($res = mysqli_fetch_array($sql)){
  $cdid = $res['cdid'];
  $fname = $res['family_name'];    
  $autocompletiondata[$cdid] = $fname; // <== make this change to your code
}

答案 2 :(得分:0)

试试这个

$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] = $fname;
}

打印数组
print_r($autocompletiondata);

答案 3 :(得分:0)

它只是使用下面的代码

$autocompletiondata =  array();
$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] = $fname;
}

希望这有助于你

答案 4 :(得分:0)

只需将数据设置为$ autocompletiondata:

$autocompletiondata = array();
while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata [$cdid] = $fname;
}