我想用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);
答案 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);