PHP-将来自不同查询的MySQL结果存储到数组中

时间:2019-11-11 03:36:45

标签: php mysql

例如,表结构如下:

Table 1          Table 2
+------+-----+   +-------+----------+
| Name | Age |   | Class | Location |
+------+-----+   +-------+----------+
| JACK | 15  |   | 205   | LDK      |
+------+-----+   +-------+----------+
| JOHN | 15  |   | 205   | KKD      |
+------+-----+   +-------+----------+
| JESS | 16  |   | 206   | MMA      |
+------+-----+   +-------+----------+

运行2个select查询后,我期望的数组应采用以下方式:

Array
(
    [0] => Array
    (
        [name] => Jack
        [age] => 15
        [class] => 205
        [location] => LDK
    )
    [1] => Array
    (
        [name] => John
        [age] => 15
        [class] => 205
        [location] => KKD
    )
    ...
)

我的代码:

$sql="select * from table1";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)){
    $arr[]=$row;
}

$sql2="select * from table2";
$result2 = $conn->query($sql2);
while ($row2 = mysqli_fetch_assoc($result)){
    $arr[]=$row2;
}

但是结果变为:

Array
(
    [0] => Array
    (
        [name] => Jack
        [age] => 15
    )
    [1] => Array
    (
        [name] => John
        [age] => 15
    )
    ...

    [3] => Array
    (
        [class] => 205
        [location] => LDK
    )
    [4] => Array
    (
        [class] => 205
        [location] => KKD
    )
    ...
)

有什么方法可以实现我预期的数组结果?谢谢!

1 个答案:

答案 0 :(得分:1)

理想情况下,应该有一个列链接两个表中的值,然后您可以将查询以JOIN的形式编写,并确保每次运行代码时都能获得期望的结果。鉴于没有一个,最好的办法是逐行读取两个结果集并合并每个查询的结果:

$sql="select * from table1";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)){
    $arr[]=$row;
}

$sql2 = "select * from table2";
$result2 = $conn->query($sql2);
$rownum = 0;
while ($row2 = mysqli_fetch_assoc($result2)){
    $arr[$rownum] = array_merge($arr[$rownum] ?? [], $row2);
    $rownum++;
}