Alex Polo
Alex Polo

Reputation: 905

How to create such a PHP array in JavaScript?

How to create such a PHP array in JavaScript?

$arr = array('oneKey' => array('key1' => 'value1',
                               'key2' => 'value2'),
             'anotherKey' => array('key1' => 'value1',
                                  'key2' => 'value2'));

EDIT: Guys, I forgot to mention that I would then need a simple way to sort those array('key1' => 'value1', 'key2' => 'value2') lexicographically by its keys.

EDIT2: Actually I won't "convert" it. It's a way I explain things. I am more of a php guy.

Upvotes: 1

Views: 104

Answers (3)

BalusC
BalusC

Reputation: 1109655

Create a JS object. The {} signifies start and end of an object and the : signifies a key-value separator, the , signifies a property (key-value pair) separator.

var obj = {
    'oneKey': {
        'key1': 'value1',
        'key2': 'value2'
    },
    'anotherKey': {
        'key1': 'value1',
        'key2': 'value2'
    }
};

alert(obj.oneKey.key2); // value2
alert(obj['anotherKey']['key1']); // value1

See also:

Upvotes: 2

Joe Mastey
Joe Mastey

Reputation: 27119

If you're sending it over AJAX, consider encoding it in JSON and parsing it back into an array on the javascript side. For the record, it's more of an object in Javascript, since it has keys and values.

In PHP:

$jsonString = json_encode($arr);

Then in JS:

var jsonObject = JSON.parse(str);

Many JS libraries have JSON parsers available to them. Otherwise, grab the one at the above link. No eval().


On sorting, simply specify the keys in the order you want them in PHP, and they should come back intact.

Upvotes: 5

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

<?php


$arr = array('oneKey' => array('key1' => 'value1',
                               'key2' => 'value2'),
             'anotherKey' => array('key1' => 'value1',
                                  'key2' => 'value2'));
?>

<script type="text/javascript">
/* <![CDATA[ */

var _my_var = '<?= json_encode($arr) ?>';

/* ]]> */
</script>

EDIT:

if you need to have the keys ordered I recomend you use ksort on the php side before use it with javascript

Upvotes: 2

Related Questions