0

I have a php multidimensional array that I am sending to jquery but I need to automatically create the array.

All the examples show setting up a manual array like so:

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

current_theme_meta and theme_metadata are keys in php array I built and I push to jQuery via wp_localize_script() (a wordpress function.)

theme_name, version, dataA, and dataB are key values inside the array.

My array looks like this:

[current_theme_meta] => Array
    (
        [theme_name] => A Cool Theme
        [version] => 2.1.1
    )

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

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

How do I create the array in jquery? I am confused between each and loop, etc.

2 Answers 2

1

json_encode in your PHP, then parse the json in your jQuery:

$json = json_encode($your_array); 

Then access it, and parse it in your Javascript:

var yourArray = JSON.parse('<?php echo $json ;?>'); 

JSON similar to XML is great for exchanging data between languages, as most languages have built in functions for dealing with it - as you can see in this example.

Sign up to request clarification or add additional context in comments.

Comments

1

A quick and easy way to do it would be to encode your PHP array as JSON using json_encode, and then pass it to your JavaScript.

An example would be:

<?php
    //Create & populate your PHP array
    $my_php_array = array(
        'foo'  => 'bar',
        'test' => array(
                'abc' => '123'
            )
    );
?>

<script type="text/javascript">
    var my_javascript_object = JSON.parse("<?php echo json_encode($my_php_array); ?>");
</script>

After that, you can access your JavaScript object as such:

<script type="text/javascript">
    alert(my_javascript_object.foo);
    alert(my_javascript_object.test.abc);
</script>

2 Comments

That does sound like the easiest way...so I basically do not need to setup the array on the jquery side as the key => value will just be passed and I can call the key/value pair. Thanks, I will play around with how to pass the array as json from inside wordpress.
Yes, that's exactly it. You'll do all your array building/manipulation in PHP, and pass the completed array as a JSON string, which is then parsed by JavaScript into an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.