0

From PHP I am pushing a basic array to jQuery via wp_localize_script() and then using the array data in my script file.

Now I have extended the array into a multidimensional array and can not figure out how to get the data out of the array to use in in the javascript file.

Currently I'm extracting the data from the array is like this:

jQuery(document).ready(function($){ 
    var optionA = theme_metadata.dataA;
    var optionB = theme_metadata.dataB;

theme_metadata is the array that I built in PHP and push to jQuery via wp_localize_script().

dataA and dataB are keys in the array.

My new array looks like this:

[theme_meta] => Array
    (
        [0] => Array
            (
                [dataA] => foo
                [dataB] => bar
            )

        [1] => Array
            (
                [dataA] => this
                [dataB] => that
            )
    )

How do I setup my var in the script file to read [theme_meta][0][dataB]?

Also how can I loop through the array? The numbered key index will not be known, i.e., [0]- whatever [100]?

I could send over a key=>value on how big the array is as a stopping point for a loop, i.e., 'theme_meta_size' => 2 as in the sample array.

1

Accessing the data

var data0A = theme_metadata[0].dataA,
    data0B = theme_metadata[0].dataB,
    data1A = theme_metadata[1].dataA,
    data1B = theme_metadata[1].dataB;

[Update] Iterating over numeric arrays in JS
While the initial question was still somewhat pertinent to WordPress, your follow-up really is a question purely concerning javascript syntax. Anyway, this is how:

var dataA,
    dataB;

for ( var i = 0; i < theme_metadata.length; i++ ) {
    dataA = theme_metadata[i].dataA;
    dataB = theme_metadata[i].dataB;
    // do something with the data
}
  • thanks, how can I loop through the array? The numbered key index will not be known, i.e., [0]- whatever [100]. I could send over a key=>value on how big the array is. – Jason Aug 5 '13 at 16:31
  • 1
    @Jason Take a look at the jQuery API documentation. – kaiser Aug 5 '13 at 16:43
  • @kaiser...Could your narrow the search down for me some, if I knew what I didn't know then I wouldn't need to post the question because I would already know how to look it up. – Jason Aug 5 '13 at 17:03
  • @Jason Your question is already off topic here. Better ask such stuff on SO or search Google for "loop data jquery" or something like that. – kaiser Aug 5 '13 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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