【发布时间】:2018-08-13 07:13:24
【问题描述】:
我像这样用PHP输出一个多维数组的json数据(已经简化了):
// query for education
$q = "SELECT ID, name, surname, email FROM education WHERE age='$age'";
$r = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($r);
$data = array();
if($num_rows > 0) {
$rows_education = array();
while ($row = mysql_fetch_assoc($r)) {
$row_array['ID'] = $row['ID'];
$row_array['name'] = $row['name'];
$row_array['surname'] = $row['surname'];
$row_array['email'] = $row['email'];
array_push($rows_education, $row_array);
}
$data['success'] = true;
$data['record']['computer'] = $rows_computer; // comes from another query
$data['record']['education'] = $rows_education;
} else {
$data['success'] = false;
}
header('Content-Type: application/json');
echo json_encode($data);
在客户端,我使用这个 JS 代码:
function View(e) {
$.ajax({
type: "GET",
url: "s_myfile.php?op=get",
data : {
ID: e.data.record.ID
},
dataType: "json",
success: function(j)
{
console.log(j);
var c = Object.keys(j.record.education).length;
alert(c);
},
error: function(data) {
console.log(data);
}
});
}
我的问题是,Object.keys(j.record.education).length 给了我键的数量,即 4。但我想获得 mysql_query ($num_rows) 返回的行数,即一个动态的结果。如何获取(记录)对象中的对象(教育)数量?
【问题讨论】:
-
您不会将该值存储在返回数据中。
-
已经更新了代码,忘记了while循环。
-
如果您发布
console.log(j);的输出,我认为您有更好的机会获得好的答案。您的问题是关于 Javascript,而不是 PHP。
标签: jquery arrays json ajax object