There is the following JSON code that appears by processing the array:

{ "success": true, "username": "xxx", "userid": 1, "subscriptions": [{ "name": "Counter-Strike: Global Offensive", "acquired": 1469815540, "expiring": 2147483647 }, { "name": "Unknown", "acquired": 1469815540, "expiring": 2147483647 }] } 

The array appears approximately as follows:

 $info['subscriptions'][$i]['acquired'] = $res[$i]['acquired']; $info['subscriptions'][$i]['expiring'] = $res[$i]['expiring']; 

But you need JSON to look like this:

 { "success": true, "username": "xxx", "userid": 1, "subscriptions": { "1": { "name": "Auto", "acquired": 0, "expiring": 0 }, "2": { "name": "Manual", "acquired": 0, "expiring": 0 } } } 

Already do not understand what to do.

    2 answers 2

    Starting with PHP 5.3, the JSON_FORCE_OBJECT option appeared :

    Output an object instead of an array using a non-associative array. This is useful when the receiving program or code is waiting for an object or if the array is empty.

    Example:

     $someArray = [ 'hello' => [ ['a' => 'b'], ['c' => 'd'], ], ]; echo json_encode($someArray, JSON_FORCE_OBJECT); 

    Result:

     { "hello": { "0": { "a": "b" }, "1": { "c": "d" } } } 

    (in fact, there is still JSON_PRETTY_PRINT , but it's not about him)

      In PHP, array elements can take numeric and string values. In the first case, we are talking about an indexed array, and in the second, an associative array. You need to turn a numeric key into a string.

       $info['subscriptions']["$i"]['acquired'] = $res[$i]['acquired']; $info['subscriptions']["$i"]['expiring'] = $res[$i]['expiring']; 

      Of course, much depends on the way the array is converted to JSON, however, it should start with the key type.

      • Hm Strange. Made it like this: $info['subscriptions']["$i"]['acquired'] = $res[$i]['acquired']; , nothing in the JSON result has changed. Could it be somehow wrong to create JSON? I use finally json_encode($info); . - Purixi
      • The following code <? Php $ info = []; $ info ['subscriptions'] = []; $ i = 1; $ info ['subscriptions'] ["$ i"] ['acquired'] = 1469815540; $ info ['subscriptions'] ["$ i"] ['expiring'] = 2147483647; $ i = 2; $ info ['subscriptions'] ["$ i"] ['acquired'] = 1469815540; $ info ['subscriptions'] ["$ i"] ['expiring'] = 2147483647; echo "<pre>"; echo json_encode ($ info); gives the correct keys {"subscriptions": {"1": {"acquired": 1469815540, "expiring": 2147483647}, "2": {"acquired": 1469815540, "expiring": 2147483647}}} - cheops
      • As if I used your answer, it didn’t fit, but @xEdelweiss wrote me about this magic flag and I was crap from life. Unfortunately, there are no two answer tags. :( - Purixi