使用php中的json_encode打印多个表查询

时间:2016-08-22 18:21:48

标签: php mysql json

我需要使用json_encode()打印多个数据库查询。我在下面的代码中使用json_encode输出数据库记录。这很好。

<?php

error_reporting(0);
include('db.php');

$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());

$data = array();

while ($row = $result->fetch()) {
    $data[] = $row;
}

echo json_encode($data);

?>

我需要添加另一个数据库查询,以便我可以使用相同的json_encode将它们打印在一起。这是我想要添加的数据库查询,以便我可以使用json_encode打印它们:

<?php

include('db.php');

$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());

$data_pro = array();

while ($row = $result->fetch()) {
    $data_pro[] = $row;
}

echo json_encode($data_pro);
?>

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我认为这可能会达到你想要的目的。

<?php

error_reporting(0);
include('db.php');

$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());

$data = array();

while ($row = $result->fetch()) {
    $data[] = $row;
}

$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());

$data_pro = array();

while ($row = $result->fetch()) {
    $data_pro[] = $row;
}

// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;

echo json_encode($all_data);