Converting a PHP associative array to a JSON associative array

Posted by Extrakun on Stack Overflow See other posts from Stack Overflow or by Extrakun
Published on 2010-03-09T06:38:44Z Indexed on 2010/03/09 6:51 UTC
Read the original article Hit count: 366

Filed under:
|
|

I am converting a look-up table in PHP which looks like this to JavaScript using json_encode:

 AbilitiesLookup Object
(
[abilities:private] => Array
    (
        [1] => Ability_MeleeAttack Object
            (
                [abilityid:protected] => 
                [range:protected] => 1
                [name:protected] => MeleeAttack
                [ability_identifier:protected] => MeleeAttack
                [aoe_row:protected] => 1
                [aoe_col:protected] => 1
                [aoe_shape:protected] => 
                [cooldown:protected] => 0
                [focusCost:protected] => 0
                [possibleFactions:protected] => 2
                [abilityDesc:protected] => Basic Attack
            )
            .....snipped...

And in JSON, it is:

{"1":{"name":"MeleeAttack","fof":"2","range":"1","aoe":[null,"1","1"],"fp":"0","image":"dummy.jpg"},....

The problem is I get a JS object, not an array, and the identifier is a number. I see 2 ways around this problem - either find a way to access the JSON using a number (which I do not know how) or make it such that json_encode (or some other custom encoding functions) can give a JavaScript associative array.

(Yes, I am rather lacking in my JavaScript department).

Note: The JSON output doesn't match the array - this is because I do a manual json encoding for each element in the subscript, before pushing it onto an array (with the index as the key), then using json_encode on it. To be clear, the number are not sequential because it's an associative array (which is why the JSON output is not an array).

© Stack Overflow or respective owner

Related posts about php

Related posts about JavaScript