Jason
Jason

Reputation: 462

Create an array in jquery from a php multidimensional array

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.

Upvotes: 0

Views: 1479

Answers (2)

Alessandro Bassi
Alessandro Bassi

Reputation: 427

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>

Upvotes: 1

JohnnyFaldo
JohnnyFaldo

Reputation: 4161

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.

Upvotes: 1

Related Questions