【问题标题】:jQuery: Get count of members of an object inside an objectjQuery:获取对象内对象的成员数
【发布时间】: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


【解决方案1】:

要遍历对象键,请使用 Object.keys(ObjectToIterateThrough)。但是j.record.education 的类型(可能)已经是一个数组,所以你可以直接访问长度:j.record.education.length

下面的示例说明了数组和对象之间的区别以及如何使用这两种类型实现相同的目的:

var myObject = {
    uuid_1: { prop1: 1, prop2: 2 },
    uuid_2: { prop1: 3, prop2: 4 },
};
var myArray = [
    { uuid: 1, prop1: 1, prop2:2 },
    { uuid: 2, prop1: 3, prop2:4 },
];
// Iterate through object:
Object.keys(myObject).forEach(key => console.log(key, myObj[key]) );
// Iterate through array:
myArray.forEach(item => console.log(item.uuid, item) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2021-05-14
    • 2012-02-10
    相关资源
    最近更新 更多