PHP存储sql查询数组,使用数组索引访问每一列

时间:2018-06-05 08:29:18

标签: php

我看过这个问题/答案How do I store all results from an SQL query in a multidimensional array? 但它不是我想要的,在这个答案中,数组索引是行,所以array [0]将包含第一行。

我想要的是array [0]包含第一列。 array [1]包含第二列。从sql查询中只返回一行。

我该怎么做?

(还没试过我手机上的代码)

这会有用吗?

$data = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
  $data[] = $row; // add the row in to the results (data) array
  $newArray = explode(",", $data[0]);
  echo $newArray[0]//return first column?
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    $count = count($row);
    for($i = 0; $i < $count; $i++) {
        $data[$i][] = $row[$i];
    }
}

测试输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [1] => Array
        (
            [0] => column 1.2
            [1] => column 2.2
            [2] => column 3.2
            [3] => column 4.2
        )

    [2] => Array
        (
            [0] => column 1.3
            [1] => column 2.3
            [2] => column 3.3
            [3] => column 4.3
        )

    [3] => Array
        (
            [0] => column 1.4
            [1] => column 2.4
            [2] => column 3.4
            [3] => column 4.4
        )

)