SitePoint Sponsor

User Tag List

Results 1 to 22 of 22
  1. #1
    SitePoint Member
    Join Date
    Sep 2003
    Location
    Norwich
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Converting a PHP array into a Javascript array, and onClick

    First of all, I'm a complete javascript newbie - go easy on me! I was told this was a friendly helpful place, so I thought it'd be a good idea to post my question here.

    Here's what I want to do:
    I have a big PHP array which holds various options.

    PHP Code:
    $ARRAY['type1']['someoption1'] = 1;
    $ARRAY['type1']['someoption2'] = 0;
    $ARRAY['type1']['someoption3'] = 0;
    $ARRAY['type1']['someoption4'] = 1;

    $ARRAY['type2']['someoption1'] = 0;
    $ARRAY['type2']['someoption2'] = 1;
    $ARRAY['type2']['someoption3'] = 0;
    $ARRAY['type2']['someoption4'] = 1;

    // etc. 
    On an HTML page I have a form with two radio buttons for each option in the above array. (Yes/No) At the top of the page, I have a selection of buttons representing ['typeX'] , each with an "onClick" property.

    What I want to happen is that when you click on a button, the options for that type will appear in the form, using the settings from the PHP array.

    How can I do this? I presume I'm going to need to convert the PHP array into a javascript one, can this be done?

    Thanks in advance for any help.

  2. #2
    SitePoint Zealot
    Join Date
    Aug 2002
    Posts
    168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    can do!

    Hey Shaolyen
    An option for doing this, not necessarily the most correct I guess, is to just echo the javascript array to the client side script.
    PHP Code:
    <script type="text/javascript">
     var aTypes = new Array();
    <?php
     $ARRAY
    ['type1']['someoption1'] = 1
     
    $ARRAY['type1']['someoption2'] = 0
     
    $ARRAY['type1']['someoption3'] = 0
     
    $ARRAY['type1']['someoption4'] = 1
     
     
    $ARRAY['type2']['someoption1'] = 0
     
    $ARRAY['type2']['someoption2'] = 1
     
    $ARRAY['type2']['someoption3'] = 0
     
    $ARRAY['type2']['someoption4'] = 1;
     
     foreach (
    $ARRAY as $var1 => $val1)
     {
      echo 
    'aTypes["'$var1 .'"] = new Array();';
      echo 
    "\n";
      
      foreach (
    $val1 as $var2 => $val2)
      {
       echo 
    'aTypes["'$var1 .'"]["'$var2 .'"] = '$val2 .';';
       echo 
    "\n";
      }
     } 
    ?>
    </script>
    which should result in something like...

    Code:
    <script type="text/javascript">
     var aTypes = new Array();
    aTypes["type1"] = new Array();
    aTypes["type1"]["someoption1"] = 1;
    aTypes["type1"]["someoption2"] = 0;
    aTypes["type1"]["someoption3"] = 0;
    aTypes["type1"]["someoption4"] = 1;
    aTypes["type2"] = new Array();
    aTypes["type2"]["someoption1"] = 0;
    aTypes["type2"]["someoption2"] = 1;
    aTypes["type2"]["someoption3"] = 0;
    aTypes["type2"]["someoption4"] = 1;
    </script>

  3. #3
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Those aren't really javascript arrays - those are objects. I've had the argument with someone before that javascript objects are associative arrays, but don't be fooled, they aren't associative arrays like you know them in PHP.

    I'll explain in greater detail if you don't understand.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  4. #4
    SitePoint Zealot
    Join Date
    Aug 2002
    Posts
    168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey beetle..

    I've always used this type of method and I guess I have always considered them to be associative arrays in JS, without ever really thinking about it too much, so by all means continue, I am most interested in your feedback.

    Cheers

  5. #5
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, here's the lowdown as best as I understand, and can describe it.

    First of all, a couple things about JS.
    1) Everything is an object. Even primitives have methods and properties (such as String.indexOf).
    2) JSObjects support two methods of reference: dot-syntax, and bracket-syntax. Object.property is the same as Object['property'].

    By reasoning of these two rules, and observing the following code
    Code:
    var arr = new Array();
    arr['index1'] = "value1";
    We can reason that index1 is actually a property that we're attaching to this instance of the Array object, and not a named (or keyed) index. This is the same as doing:
    Code:
    arr.index1 = "value";
    So far, it still looks like an associative array -- mostly. I should take a moment to expound on the syntax differences. Dot-syntax allows only alphanumeric characters in for property names that must start with an alpha character, or the underscore, just like variables. This is partly because it's bad practice, and partly because it can cause problems with Array objects, which we'll see later. Since using bracket syntax allows you to assert the property names as strings, you can both create and reference what would normally be invalid property tokens. It is this very reason why we must use the elements collection to reference form elements whose name contains a space, or is itself named like an array (form.elements['chexbox[]']), or some other non-alphanumeric character.

    Now, let's look at a regular array in JS and, being an object, some of the properties it has
    Code:
    var arr = [1,2,3,4]; // literal notation
    alert( arr.length ); // 4
    alert( arr[2] ); // 3
    We can see that each numerical index is included in it's length property, and that the numerical indexes are behaving as expected. Now, let's toss a monkey wrench in here.
    Code:
    arr['10'] = 10;
    What did I just create? A property? Or an index? According to my rules, the above should be a property named 10. Let's see
    Code:
    alert( arr ); // 1,2,3,4,,,,,,,10
    Ahhh, so it's not a property after all! According to the alert, I just stored the number 10 into the 10th index of the array. Herein lies the exception to the rule, and why I feel javascript doesn't provide a true associative data structure to the user.

    If arr was an instance of Object, and not Array, then arr['10'] would be a property, albeit one only accessed by the bracket notation per javascript tokenization rules. But, since arr is not an Object instance, the language interprets my ['10'] as [10], therefore disallowing me to create an array with named keys that are solely numeric in composition while simultaneously disallowing me to create a property named 10 as well.

    Furthermore, properties added to an Array object aren't part of it's vector - meaning the length property doesn't count for their existence, nor will an iterative loop catch them. A for...in loop does, however, it will also grab any other user-defined properties on the page as well - something I couldn't handle, since I use object extensions regularly.

    So, both Object and Array give an associative array implementation to the user, as I see it, only halfway. It is only because Javascript's script engine implements everything as objects, that we are allowed to add named properties. By that reasoning, you might as well use any datatype to build your associative array on, such as Function, String, or Boolean -- which I think we all recognize is just a no-no.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  6. #6
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent stuff there, beetle

  7. #7
    SitePoint Member
    Join Date
    Sep 2003
    Location
    Norwich
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <makes a way over my head gesture>

    Um... would it be a bad idea to do it grahowler's way?

  8. #8
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What did I just create? A property? Or an index? According to my rules, the above should be a property named 10. Let's see
    Code:
    alert( arr ); // 1,2,3,4,,,,,,,10
    Ahhh, so it's not a property after all! According to the alert, I just stored the number 10 into the 10th index of the array.
    Interesting... Does this have anything to do with automatic type conversion (of the subscript) or is it just because an identifier can't begin with a digit?

  9. #9
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    grahowler's way is fine, just so long as you understand that you're really making an object, that the named values (properties) aren't part of what makes up the array's length.

    Mike -
    I'm guessing type conversion, because
    Code:
    var o = new Object();
    o['10'] = "ten";
    alert( o['10'] );
    Works. Only the an instance of Object allows this (numbered identifier), that I've been able to determine.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  10. #10
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried something like...
    Code:
    var a = new Array();
    var i = 10;
    a[i.toString()] = 10;
    but got the same results. I guess there's no real 'type cast' in js.

    Thanks, beetle!

  11. #11
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Like I said, essentially, everything in JS is an object. This is why I wish the instanceOf operator had better support
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  12. #12
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi beetle,

    just to add:

    PHP Code:
    arr = new Array();
    arr[10] = 1
    arr
    ['10'] = 2;  
    arr["" 10] = 'some10';
    arr["" 10 ""] = 'some';  //overwrites everything above

    arr["'10'"] = 'noNum';  //  'property'/'associative array'

    alert(arr.length)  // 11

    for (0arr.lengthi++)
    alert("for loop: " +' = ' arr[i]) //alerts 10 'undefined' and 1 'some'

     
    for (i in arr)
    alert('for in loop: ' ' = ' arr[i]) // alerts 'some' and 'noNum'

    alert('arr[10] = ' arr[10])  // alerts 'some'

     
    ch "'10'";
    alert('arr.ch = ' arr.ch)  
    alert('arr[ch] = ' arr[ch])
    alert('toString = ' arr[ch.toString()]) 
     
     var 
    10
    alert
    (arr['"' +y.toString() + '"']) //alerts undefined - single double single quotes
    alert(arr["'" +y.toString() + "'"]) // alerts noNum double single double quotes
    alert(arr["" +y.toString() + ""]) // alerts some empty quotes 
    the most interesting (imo) are the last three.

    Vinny
    Where the World Once Stood
    the blades of grass
    cut me still

  13. #13
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't see anything new here. Basically you've re-asserted everything I've already established

    1) Numeric-only string keys are translated into numerical indicies
    2) Non-aplhanumeric, non-numeric-only properties can be created and referenced using bracket notation.

    Am I missing something?
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  14. #14
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Basically you've re-asserted everything I've already established
    True...
    However unless I'm missing something, the first 2 alerts should alert the same result -- 'noNum' -- because they are not numerical idicies. Is it that -- "10" does not equal '10' -- which would explain why the first alert reports 'undefined' ?
    PHP Code:
    [font=Courier][color=#0000cc]alert[/color][color=#006600]([/color][color=#0000cc]arr[/color][color=#006600][[/color][color=#cc0000]'"' [/color][color=#006600]+[/color][color=#0000cc]y[/color][color=#006600].[/color][color=#0000cc]toString[/color][color=#006600]() + [/color][color=#cc0000]'"'[/color][color=#006600]])[/color][/font]
    [font=Courier][color=#0000cc]alert[/color][color=#006600]([/color][color=#0000cc]arr[/color][color=#006600][[/color][color=#cc0000]"'" [/color][color=#006600]+[/color][color=#0000cc]y[/color][color=#006600].[/color][color=#0000cc]toString[/color][color=#006600]() + [/color][color=#cc0000]"'"[/color][color=#006600]]) [/color][/font]
    [font=Courier][color=#006600][color=#0000cc]alert[/color][color=#006600]([/color][color=#0000cc]arr[/color][color=#006600][[/color][color=#cc0000]"" [/color][color=#006600]+[/color][color=#0000cc]y[/color][color=#006600].[/color][color=#0000cc]toString[/color][color=#006600]() + [/color][color=#cc0000]""[/color][color=#006600]]) [/color][/color][/font]
    [color=#ff9900][color=#000000][/color][/color] 

    However, if I declare :
    PHP Code:
    arr["'10'"] = 'noNum'//single in double
    arr['"10"'] = 'doubleInsingle'
    The first assignment gets overwritten; thereby implying the quotes are immaterial.


    Vinny

    Where the World Once Stood
    the blades of grass
    cut me still

  15. #15
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    no idea where that stuff came from

    Vinny
    Where the World Once Stood
    the blades of grass
    cut me still

  16. #16
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Looks like the would-be coloring of PHP code. It got messed up somehow.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  17. #17
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So, what do you think?
    Are quotes being handled differently by assignment & methods (concat, alert)?

    Why does the first alert result in an undefined?

    btw: am I the 'someone' (i seem to recall something like that, though I wouldn't have called it an argument)
    I've had the argument with someone before that javascript objects are associative arrays
    Vinny
    Where the World Once Stood
    the blades of grass
    cut me still

  18. #18
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't see the behavior you're describing, unless I've missed something
    Code:
    var a = new Array();
    a[10] = "number";
    a['"10"'] = "singleThenDouble";
    a["'10'"] = "doubleThenSingle";
    
    alert( "Array: " + a );
    
    for ( var i = 0; i < a.length; i++ )
    {
    	alert( "For Loop: " + i + " = " + a[i] );
    }
    
    for ( var p in a )
    {
    	alert( "For in Loop: " + p + " = " + a[p] );
    }
    I get the exact same output from IE6, Mozilla 1.4, and Opera 7.11
    Array: ,,,,,,,,,,number

    For Loop: 0 = undefined
    For Loop: 1 = undefined
    For Loop: 2 = undefined
    For Loop: 3 = undefined
    For Loop: 4 = undefined
    For Loop: 5 = undefined
    For Loop: 6 = undefined
    For Loop: 7 = undefined
    For Loop: 8 = undefined
    For Loop: 9 = undefined
    For Loop: 10 = number

    For in Loop: 10 = number
    For in Loop: "10" = singleThenDouble
    For in Loop: '10' = doubleThenSingle
    The quotes are acting like they should, as regular characters, and not any form of delimeter.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  19. #19
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry beetle,
    It has to be my system. my original code no longer does what it did. and I'm having trouble sending emails.

    Vinny
    Where the World Once Stood
    the blades of grass
    cut me still

  20. #20
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No problem, I just wanted to make sure for the benefit of those reading, we had this figured out.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  21. #21
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think you’ve all been blinded to the real question in this post:
    Quote Originally Posted by Shaolyen
    What I want to happen is that when you click on a button, the options for that type will appear in the form, using the settings from the PHP array.
    All he is asking to do here is to show/hide a <div> full of check-boxes depending on the state of another check-box, or a button on the form. It is not necessary to convert the PHP array into a JavaScript array for this.

    Peter-Paul Koch has some good examples of dynamic-forms like this:

    http://www.xs4all.nl/~ppk/js/index.h...ableforms.html
    http://www.xs4all.nl/~ppk/js/index.html?domform.html (Article)
    Of course, that's just my opinion. I could be wrong.

  22. #22
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I PM'ed him a while ago to make sure he got the help he needed, and he was satisfied - it was only because of that, that I pursued the off topic discussion. I couldn't be a good Mentor without doing so
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev





Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •