Convert PHP associative array to JSON associative array

I am converting a lookup table to PHP which looks like this in 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, this is:

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

The problem is that I am getting a JS object, not an array, and the identifier is a number. I see two ways to solve this problem: either find a way to access JSON using a number (which I don’t know), or make it so that json_encode (or some other custom encoding functions) can give an associative JavaScript array.

(Yes, I miss my JavaScript department).

: JSON - , json- , ( ), json_encode. , , ( JSON ).

+3
2

JavaScript . ( ), /:

var obj = {
    "1": "foo",
    "2": "bar"
};

obj["1"]; // returns "foo"
obj[1]; // returns "foo" (1 will implicitly get cast to the string "1")
+9

array ('a', 'b', 'c') ['a', 'b', 'c'],

, , php- 1, 0

<?php
echo json_encode(array('a', 'b', 'c'))."\n";
echo json_encode(array(0 => 'a', 'b', 'c'))."\n"; // same as above but explicit
echo json_encode(array(1 => 'a', 'b', 'c'))."\n";

["a","b","c"]
["a","b","c"]
{"1":"a","2":"b","3":"c"}
+12

Source: https://habr.com/ru/post/1736064/


All Articles