简体   繁体   English

如何从php中生成的数组获取javascript中的长度?

[英]How to the get a length in javascript from an array generated in php?

I use jQuery to call a php function and return an array. 我使用jQuery调用php函数并返回一个数组。 Here is the php code: 这是PHP代码:

  $users = array();
  $user = array();

  $user["fname"] = "Juan";
  $user["lname"] = "Perez";
  $user["uname"] = "jperez";
  $user["passwd"] = "passwd1234";
  $user["rights"] = array(
  "mod_own" => true,
  "view_all" => false,
  "mod_all" => true,
  "mod_proj" => false,
  "mod_users" => true
  ); 

  $users[1] = $user;

  $user["fname"] = "Pedro";
  $user["lname"] = "Rodriquez";
  $user["uname"] = "pedror";
  $user["passwd"] = "passwd456+";
  $user["rights"] = array(
  "mod_own" => false,
  "view_all" => true,
  "mod_all" => false,
  "mod_proj" => true,
  "mod_users" => false
  ); 

  $users[1] = $user;
  $ret["users"] = $users;
  $ret["error"] = "";

  echo json_encode($ret);

This is just a test code of what I really want to return. 这只是我真正想要返回的测试代码。 The thing is that I know that users has a length 2 here, but in the real applicaction I won't know that. 事实是,我知道用户的长度为2,但是在实际应用中,我不会知道。 I want to check its length. 我想检查一下它的长度。 In the javascript that calls this function the returning object is call obj. 在调用此函数的javascript中,返回对象是obj。 If I say 如果我说

obj.users[1]['fname'] obj.users [1] ['fname']

I get the correct name and everything. 我得到正确的名字和所有的东西。 What I don't know how to do is check the length of users. 我不知道该怎么做是检查用户的长度。 I have tried obj.users.length but it doesn't work. 我试过obj.users.length,但是不起作用。

How do I check that? 我该如何检查?

EDIT: 编辑:

To see the length I used this code: 要查看长度,我使用了以下代码:

document.getElementById("debug").innerHTML="N de users is " + obj.users.length;

I got "N de users is undefined" 我收到了“ N de users is undefined”

You're setting $users[1] twice without setting $users[0] . 您两次设置$users[1]而不设置$users[0] This will output an Object , which does not have a length property. 这将输出一个没有length属性的Object Instead of specifying the index directly, just push your content into $users : $users[] = $user . 无需直接指定索引,只需将您的内容推送到$users$users[] = $user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM