Search code examples
phpjsonencode

PHP Convert to JSON Object


I have an associative array that I need to convert to a very specific JSON string. Currently my array looks like this:

$arr = array(
    array(
        'data' => array(
            'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5
        ),
        array(
            'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5
        )
    )
);

this JSON encodes as:

[{"data":{"a":1,"b":2,"c":3,"d":4,"e":5},"0":{"a":1,"b":2,"c":3,"d":4,"e":5}}]

I need the JSON to look like this:

{"data":[{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}]}

Keep in mind that this is a representation on my array and that it can vary in size. Currently it has two records but most likely it will have more.

How do I encode my array to match my requirement?


Solution

  • Try this:

    $arr = array(
           'data' => array(
            0=>array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5),
            1=>array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5)
            )
    );
    

    For me this produces:

    {"data":[{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}]}