在PHP MySQL中联接表时的二维数组

时间:2018-10-19 08:23:09

标签: php mysql

我有下表projects

+----+----------+-------+------------+
| id | name     | admin | timestamp  |
+----+----------+-------+------------+
|  1 | Group1   |     2 | 1539678214 |
|  2 | Test     |     2 | 1539678214 |
+----+----------+-------+------------+

还有users

+----+----------------+------------------------+
| id | name           | email                  |
+----+----------------+------------------------+
|  1 | FOO            | foo@bar.com            |
|  2 | BAR            | bar@foo.com            |
|  3 | G2W            | far@boo.com            |
+----+----------------+------------------------+

我运行以下SQL命令:

SELECT projects.id,projects.name,users.id as userid,users.email 
FROM projects 
INNER JOIN users ON users.id=projects.admin;

我得到以下结果:

+----+----------+--------+-----------------+
| id | name     | userid | email           |
+----+----------+--------+-----------------+
|  1 | Group1   |      2 | bar@foo.com     |
|  2 | Test     |      2 | bar@foo.com     |
+----+----------+--------+-----------------+

这很完美,这正是我所需要的。现在我的问题是,用PHP做到这一点并将结果存储在二维数组中的最佳方法是什么?

到目前为止,这是我想要的,但是我得到的结果是一个我不想要的一维数组:

$stmt = $_DB->prepare("SELECT projects.id,projects.name,users.id as userid,users.email 
                       FROM projects 
                       INNER JOIN users ON users.id=projects.admin");
if($$_DB->error) die($$_DB->error);

$stmt->execute();
$res=$stmt->get_result();
while($result[]=$res->fetch_array(MYSQLI_ASSOC)){}
print_r($result);

结果:

[0] => Array
    (
        [id] => 1
        [name] => Group1
        [userid] => 2
        [email] => bar@foo.com
    )

[1] => Array
    (
        [id] => 2
        [name] => Test
        [userid] => 2
        [email] => bar@foo.com
    )

这就是我想要的:

[0] => Array
    (
        [id] => 1
        [name] => Group1
        [admin] => Array
            (
                [id] => 2
                [email] => bar@foo.com
            )

    )

[1] => Array
    (
        [id] => 2
        [name] => Test
        [admin] => Array
            (
                [id] => 2
                [email] => bar@foo.com
            )

    )

1 个答案:

答案 0 :(得分:2)

查询结果将始终采用表格格式(行和列)。基本上,它将是一个数组数组,其中第二级数组代表特定行。如果希望结果以多维数组形式显示,则在获取查询输出后,必须使用PHP代码进行此操作:

$res=$stmt->get_result();

// Initialize result variable
$result = array();

// Get results row by row
while( $row = $res->fetch_array(MYSQLI_ASSOC) ) {

    // In a temp variable, create the multi-dim array as you wish
    $temp['id'] = $row['id'];
    $temp['name'] = $row['name'];
    $temp['admin'] = array('id' => $row['userid'], 
                           'email' => $row['email']);

    // insert the temp result row
    $result[] = $temp;
}
print_r($result);