douhuan2101 2014-10-01 03:02
浏览 61
已采纳

如何使用php直接从mysql查询创建多维数组?

How can I have directly a multidimensional array from following mysql query?

$query = SELECT * FROM table WHERE field1 = 1;

I've tried the following:

$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_array($result)){
    $table[] = ($row['field1'].'~'.$row['field2'].'~'.$row['field3'].'~'.$row['field4']);
}

If we print it we have following result:

array(
    [0] => 1 ~ ALFA  ~ beta   ~ 57
    [1] => 1 ~ BETA  ~ gamma  ~ 18
    [2] => 1 ~ GAMMA ~ delta  ~ 24
    ...
    [999] => 1 ~ ZETA ~ theta ~ 19
)

Then I have to explode it to have the multidimensional array that I wish:

foreach ($table as $value) {
    $tableWithSubArrays[] = explode("~", $value);
}

And then we got it:

Array(
    [0] => Array
        (
            [0] => 1
            [1] => ALFA
            [2] => beta
            [3] => 57
    )

    [1] => Array
        (
            [0] => 1
            [1] => BETA
            [2] => gamma
            [3] => 18
    )

    ...

    [999] => Array
        (
            [0] => 1
            [1] => ZETA
            [2] => theta
            [3] => 19
    )

Is there any other way that make it directly from the query to the multidimensional array?

Many thanks in advance!

  • 写回答

1条回答 默认 最新

  • douqingzhi0980 2014-10-01 03:10
    关注
    while ($row = mysqli_fetch_array($result)){
        $table[] = $row;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据