使用PHP在一个数组中组合多个查询结果集

时间:2018-12-19 09:53:49

标签: php mysqli

我想用php将查询的多个结果合并到一个数组中。但是我很难做到。有帮助吗?

$row = $conn->query("SELECT COUNT(school_name) as school_total from schools_tbl");
$row->setFetchMode(PDO::FETCH_ASSOC);
$school_count = $row->fetchAll();

$row = $conn->query("SELECT COUNT(fname) as parents_total from parents_tbl");
$row->setFetchMode(PDO::FETCH_ASSOC);
$parent_count = $row->fetchAll();

echo json_encode($school_count,$parent_count);

2 个答案:

答案 0 :(得分:1)

您做的事情很简单...

echo json_encode(["school" => $school_count,"parent"=>$parent_count]);

但是由于这些是结果数组,因此您可能希望提取实际的计数值...

echo json_encode(["school" => $school_count[0][0],"parent"=>$parent_count[0][0]]);

答案 1 :(得分:1)

您不需要使用fetchall()来获取单个列。您可以改用fetchColumn()。

<?php

$row = $conn->query("SELECT COUNT(school_name) as school_total from schools_tbl");
$row->setFetchMode(PDO::FETCH_ASSOC);
$school_count = $row->fetchColumn();

$sql = $conn->query("SELECT COUNT(fname) as parents_total from parents_tbl");
$sql->setFetchMode(PDO::FETCH_ASSOC);
$parent_count = $sql->fetchColumn();

$results = array(
    'school_total' => $school_count,

    'parents_total' => $parent_count
);


echo json_encode($results);