SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    Super Ninja Monkey Travis's Avatar
    Join Date
    Dec 2001
    Location
    Sioux City, Iowa
    Posts
    691
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    passing a multidimensional array to javascript

    I am trying to pass a multidimensional array like this:
    Code:
    Array
    (
        [Alabama] => Array
            (
                [corp] => 90
                [llc] => 75
            )
    )
    to JS so that I can use the data in a JS function. I tried this script:
    PHP Code:
    <?php
    include('state_list.php');
    foreach (
    $state_costs as $foo => $bar) {
        foreach (
    $bar as $key => $val) {
    echo 
    "    array['{$foo}']['{$key}'] = '{$val}';\n";
        }
    }
    ?>
    which has output that looks like this:
    Code:
    array['Alabama']['corp'] = '90';
    array['Alabama']['llc'] = '75';
    However, this doesn't work. Does JS even support this? If so, how would I do it?
    Travis Watkins - Hyperactive Coder
    My Blog: Realist Anew
    Projects: Alacarte - Gnome Menu Editor

  2. #2
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, JS supports associative, or expando arrays.

    It works like this:
    Code:
    var oMyArray = new Array ( );
    
    oMyArray [ 'Alabama' ] = new Array ( );
    oMyArray [ 'Alabama' ] [ 'corp' ] = '90';
    oMyArray [ 'Alabama' ] [ 'lic' ] = '75';
    
    oMyArray [ 'Kentucky' ] = new Array ( );
    oMyArray [ 'Kentucky' ] [ 'corp' ] = '85';
    oMyArray [ 'Kentucky' ] [ 'lic' ] = '60';
    You can the access the properties like this:
    Code:
    var sAlabamaLicense = oMyArray.Alabama.lic;
    Or like this:
    Code:
    var sAlabamaLicense = oMyArray [ 'Alabama' ].lic;
    Or like this:
    Code:
    var sAlabamaLicense = oMyArray [ 'Alabama' ] [ 'lic' ];
    You get the idea.
    Of course, that's just my opinion. I could be wrong.

  3. #3
    Super Ninja Monkey Travis's Avatar
    Join Date
    Dec 2001
    Location
    Sioux City, Iowa
    Posts
    691
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, that did it.
    Travis Watkins - Hyperactive Coder
    My Blog: Realist Anew
    Projects: Alacarte - Gnome Menu Editor


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
  •