tags:

views:

52

answers:

3

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.

+2  A: 
<?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

Gabriel Sosa
I was going to edit to fix the formatting, but there's nothing there, from what I can see...
Matchu
Mmkay, see it now. Downvote revoked.
Matchu
I submited the answer by mistake, now can you please remove the down vote?
Gabriel Sosa
+5  A: 

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.

Joseph Mastey
Better answer. +1, answer revoked.
Matchu
I am not going to send it anywhere.
Alex Polo
Hmm... Actually I won't "convert" it. It's a way I explain things. I am more of a php guy...
Alex Polo
"simply specify the keys in the order you want them in PHP" - sorry, no PHP here. It is just my way of explaining things.
Alex Polo
+1  A: 

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:

BalusC
That way I can't sort, say, the anotherKey object lexicographically by its keys, right? I would need something like this: obj['anotherKey'].sort();
Alex Polo
I have done the way you suggested and got stuck with sorting.
Alex Polo
Then use a real array with index. JS doesn't support associative arrays like PHP does. See also http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
BalusC
How do you guys code in such a poor language? =)
Alex Polo