Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Problem: Trying to use 'dynamic' variables to access JSON/JavaScript arrays.

# EXAMPLE #

Instead of... array1[ ] or array2[ ] or even array9000[ ]

Somthing like... var my_array = 'array' + 'some generated number' ;

Then just... my_array[ ] or my_array[some number]

BUT this does'nt work... (sollution NOW at bottom)



I have some PHP that's reading some directories PLUS there contents to create JSON arrays. The JSON arrays are named sequentially and they are storing image directories...

Example JSON Array Names: images0, images1, images2, etc...

    <?php
        $dir = opendir(getcwd());
        $num=0;
        while($folder = readdir($dir)) {
            if($folder !== '.' && $folder !== '..'){
                if (is_dir($folder)) {
                    echo '<script type="text/javascript">';
                    $folderCHILD = opendir($folder);
                    while($image = readdir($folderCHILD)) {
                        if($image !== '.' && $image !== '..'){
                            $images[]=$folder."/".$image;
                        }
                    }
                    closedir($folderCHILD);
                    echo 'images'.$num.' ='.json_encode($images);
                    unset($images);
                    echo '</script>';
                    $num++;
                }
            }
        }
        closedir($dir);
    ?>


Then I have some Javascript/Jquery that's 'attempting' to access these sequentially named JSON arrays through a click function. The function will create an image using the image directories stored in the JSON arrays.

<script type="text/javascript">
    $(document).ready(function() {
        $('something').click(function() {
            var indexCURRENT = $(this).index();
            var ARRAY = 'images'+indexCURRENT;
            $(document.createElement("img")).attr({ src: ARRAY[some number]}).addClass("image").appendTo('body');
        });
    });
</script>

^The Above Javascipt/Jquery Doesn't Work^


But Thanks to dev-null-dweller this bit of code does work...

<script type="text/javascript">
    $(document).ready(function() {
        $('#gallery_link p').click(function() {
            var indexCURRENT = $(this).index();
            var ARRAY = 'images'+indexCURRENT;
            $(document.createElement("img")).attr({ src: window[ARRAY][some number]}).addClass("image").appendTo('body');
        });
    });
</script>

The Difference?

.attr({ src: window[ARRAY][some number]})
share|improve this question
    
try to distil down to its most basic form what you are trying to do. rewrite a test bit of code to show it, there is too much information here to follow. –  Toby Allen Apr 29 '12 at 20:51

2 Answers 2

up vote 0 down vote accepted

Quick answer: your numerated variables should be accessible in window object, accessed like array (window['images1']) so simply changing

{ src: ARRAY[1]}

to

{ src: window[ARRAY][1] }

should make it work.

Proper answer: use arrays / objects, it's simple as this:

<script>
echo '<script type="text/javascript">';
echo 'images = [];';
$folderCHILD = opendir($folder);
while($image = readdir($folderCHILD)) {
    if($image !== '.' && $image !== '..' && $folder !=='resource'){
        $images[]=$folder."/".$image;
    }
}
closedir($folderCHILD);
echo 'images.push('.json_encode($images).');';
echo '</script>';

And then:

{ src: images[indexCUR][1] }
share|improve this answer
    
Thanks! I'm gonna try it out! –  Terry Apr 29 '12 at 21:16
    
Thanks for your input, I couldn't get your 'proper' answer to work (as of yet, I'm still at it) but your 'quick' fix works great. Thank you! –  Terry Apr 29 '12 at 22:35

I'm pretty sure you cannot do that in JS. You can't use a variable content as a variable name. This is feasible in php where you can do

$varname = 'x';

$$varname = "something";

print $x; //Prints "something"

but not in javascript. Just use a multidimensional array or a hash to do that.

share|improve this answer
    
Thanks for the info, didn't know it wasn't possible in javascript. @Gaet So... I've tried tinkering with multidimensional array but I didn't get too far cuz I couldn't think of creating the multidimensional array dynamically in javascript. Thanks to your info I'm gonna try setting it up within my PHP. –  Terry Apr 29 '12 at 20:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.