在PHP中使用JSON返回多个数组
我试图通过将所有数组编码为JSON数组来返回2个数组和第三个变量。 我想要访问数组和第三个变量的所有键。我很难做到这一点。我所能做的就是这样,但没有成功 需要帮助。有没有办法将整个json_编码的数据['states']复制到JS数组中 onlineStudents.php在PHP中使用JSON返回多个数组,php,javascript,arrays,json,Php,Javascript,Arrays,Json,我试图通过将所有数组编码为JSON数组来返回2个数组和第三个变量。 我想要访问数组和第三个变量的所有键。我很难做到这一点。我所能做的就是这样,但没有成功 需要帮助。有没有办法将整个json_编码的数据['states']复制到JS数组中 onlineStudents.php <?php require_once 'myfunctions.php'; $query="Select * from online_students"; $result= queryMysql($query); $
<?php
require_once 'myfunctions.php';
$query="Select * from online_students";
$result= queryMysql($query);
$data["total"]=mysql_num_rows($result)-1;
$query="Select distinct state from online_students";
$result=queryMysql($query);
while($row= mysql_fetch_array($result))
{
$query2="select * from online_students where state='$row[state]'";
$result2=queryMysql($query2);
$data["states"]=mysql_num_rows($result2);
}
$query="Select distinct college from online_students";
$result= queryMysql($query);
while($row= mysql_fetch_array($result))
{
$query2="Select * from online_students where college='$row[college]'";
$result2=queryMysql($query2);
$data["colleges"]=mysql_num_rows($result2);
}
echo json_encode($data);
?>
myfunctions.js
function peoples()
{
$.getJSON("onlineStudents.php",function(data){
$("#chat_head_number").html(": "+data['total']);
$("#chat_states_number").html(data['states']); //i want the whole array data[states] instead of a single value
$("#chat_college_number").html(data['colleges']);
});
}
您的JSON发送和读取看起来不错。在SQL查询中,您可能需要将
{}
放在$row[state]
周围,就像{$row[state]}
一样。您是否检查了是否正确替换了这些函数?离题:请注意,PHP中的mysql\u xxx()
函数已被弃用,不鼓励使用它们。你应该考虑切换到一个新的数据库API,比如PDO库。你想用它里面的所有数据返回一个JSON对象吗?如果我们能看到您的表模式是什么样子的,那将非常有用。如果您使用两个JOIN
语句,您可以在一个步骤中完成所有操作,mysql\u fetch\u array
然后返回JSON。还建议您在编码时使用JSON_PRETTY_PRINT选项。@Cobra_Fast-但即使没有大括号,查询也可以正常运行。@Spudley-我不知道这一点。谢谢你的更新。
function peoples()
{
$.getJSON("onlineStudents.php",function(data){
$("#chat_head_number").html(": "+data['total']);
$("#chat_states_number").html(data['states']); //i want the whole array data[states] instead of a single value
$("#chat_college_number").html(data['colleges']);
});
}