Ajeesh
Ajeesh

Reputation: 43

How do I encode a normal PHP array to a JSON array keeping the indexes

Consider one simple array.

<?php
$a = array('a','b','c');
?>

how can i generate a json array as given below.

{
'0':'a',
'1':'b',
'2':'c'
}

Normal json_encode function returns ['a','b','c']

Upvotes: 0

Views: 126

Answers (2)

Anand Solanki
Anand Solanki

Reputation: 3425

Try this:

Working perfectly. I tried

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

        $new_arr = json_encode($arr);

        print_r($new_arr);
        ?>

Output

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

-

Thanks

Upvotes: 0

Emil A.
Emil A.

Reputation: 3445

Pass JSON_FORCE_OBJECT as second argument to the json_encode function.

http://php.net/manual/en/function.json-encode.php

json_encode($a, JSON_FORCE_OBJECT);

Upvotes: 5

Related Questions