0

I have a PHP object like so:

Array ( 
     [Apples] => stdClass Object ( 
                      [RandomText] => Apples 
                      [RandomNumber1] => 30 
                      [RandomNumber2] => 21 
                 ) 
     [Oranges] => stdClass Object ( 
                      [RandomText] => Oranges 
                      [RandomNumber1] => 20 
                      [RandomNumber2] => 45 
                 ) )

My ultimate goal is to be able to use this with jQuery. In particular, in a form select, once the option is changed to "Apples", it alerts "RandomString1 is greater than RandomString2", and when it's changed to Oranges, it alerts "RandomString1 is smaller than RandomString2" and so on with many more iterations.

My question is, how do I do this? I've tried adding this to my PHP:

echo '<script> var json = '. json_encode($myArray).'</script>';

which outputs:

var json = {"Apples":{"RandomText":"Apples","RandomNumber1":"30","RandomNumber2":21},"Oranges":{"RandomText":"Oranges","RandomNumber1":"20","RandomNumber2":45}}

But I cannot figure out how to proceed from here.

Any help, even pointing me where to look, would be greatly appreciated :)

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Mendel Kramer
  • 357
  • 3
  • 11

1 Answers1

4

You're almost there…

$('select').change(function(){
  var fruit = $(this).val();
  if (json[fruit].RandomNumber1 > json[fruit].RandomNumber2) {
    alert(json[fruit].RandomText);
  } else {
    alert('Something else?');
  }
});

You should probably use Inspector/Firebug to play with the JS console in your browser so you can try things out easily. You can start by just writing json; and seeing what it returns. Then start playing with different ways of navigating the tree.

coreyward
  • 77,547
  • 20
  • 137
  • 166
  • You, my friend, are awesome. Should have asked 3 hours ago :). Small note: I needed to add "json[fruit]." in front of the "RandomNumber2" as well. Thank you very much. – Mendel Kramer Sep 06 '11 at 06:09
  • @Mendel: Yeah I'm glad you caught that. I've updated the question to fix for anybody else that stumbles across this. – coreyward Sep 06 '11 at 15:46