JSON member access problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nirvanaforu
Forum Newbie
Posts: 2
Joined: Fri Nov 21, 2008 2:29 pm

JSON member access problem

Post by nirvanaforu »

Hi there:
I met a really strange problem.
Here is the problem:
Im using php 5.2's json extension. For example: I have a php variable $php_objects_array, which is an array with Objects I defined myself.
More specific, for example:

Code: Select all

<?php
class foo 
{
  var id;
  var value;
}
?>
and then $php_objs_array = {foo_1, foo_2}, where foo_1,foo_2 are two instances of class foo. To make thing clear, if I print_r($php_objs_array), the results will be like: Array([0]=>foo Object ([id]=>1, [value]=>45), [1]=>foo Object([id]=>2, [value]=>50))

Now, we want to encode this array into json so that I could pass it to javascript. Here is what I did:
$json_I_need =json_encode($php_objs_array)

now the string $json_I_need will be like: [{"id":"1","value":"45"},{"id":"2","value":"50"}]

when I pass this variable to javascript function, <javascript: test_f($json_I_need) >
I don't know how I can access this json objects, because it doesn't have members. In firebug, it just shows json_i_need has two objects, but when I tried json_i_need.Object[0].id, it always says that undefined references.

Please help! Thanks a lot!
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: JSON member access problem

Post by novice4eva »

try

Code: Select all

json_i_need[0].id
instead
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: JSON member access problem

Post by mmj »

novice4eva wrote:try

Code: Select all

json_i_need[0].id
instead
yeah.

Code: Select all

json_i_need[0]["id"]
would give the same result.
nirvanaforu
Forum Newbie
Posts: 2
Joined: Fri Nov 21, 2008 2:29 pm

Re: JSON member access problem

Post by nirvanaforu »

yes, it worked. Thanks a lot!
Post Reply