dpowt82802 2015-08-27 07:29
浏览 443
已采纳

将查询结果转换为二维数组

I want to convert my query result to two dimensional array the query is

SELECT c.name,c.mobile_number,t.service_time 
FROM CUSTOMER AS c
JOIN TRANSACTION AS t ON c.id = t.customer_id
WHERE t.service_date = '$date' 
AND employee_id = '$employee_id

I get name(varchar),mobile num(int) and time which is time format. I wrote some code but it is not working:

$results = array();
echo $num_fields=mysqli_num_fields($array1);
echo $num_rows=mysqli_num_rows($array1);
while($line = mysqli_fetch_array($array1))
{
    for($i=0;$i<$num_rows;$i++)
    {
        for($j=0;$j<$num_fields;$j++)
        {
            $results[$i][$j]=$line[$i][$j];
        }
        }
}

The result I am getting is:

[["k ","a ","r "],["9 ","8 ","7 "],["0 ","2 ",": "]]

The output contains only first characters that to one. I want each row of two dimensional array to have row of my query result.

  • 写回答

3条回答 默认 最新

  • dqj5046 2015-08-27 07:37
    关注

    You can just add the result to a new array and change mysqli_fetch_array to mysqli_fetch_row:

    $results = array();
    
    while ($line = mysqli_fetch_row($array1))
    {
      $results[] = $line;
    }
    

    Alternatively you can use mysqli_fetch_assoc() to make for an associative array (e.g. $results[0]['name'] will be the name column of the first row).

    Edit

    If there are duplicate column names you can use aliases:

    SELECT one.name AS one_name, two.name AS two_name FROM one INNER JOIN two USING ...

    The associative array will then have $result[0]['one_name'] and $result[0]['two_name'].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部