1

Something like:

[0 => 'a', 1 => 'b']

to json

{
    "0": "a",
    "1": "b",
}

instead of

["a","b"]
2
  • Is the array key an incremental value? Commented Sep 7, 2017 at 2:13
  • @FreedomPride may or may not! Commented Sep 7, 2017 at 2:37

2 Answers 2

1

This is what you're looking for. Forcing the JSON Object is the only solution you're looking for.

$array = array( '0' => 'a', '1' => 'b', '2' => 'c', '3' => 'c' );
$json = json_encode($array, JSON_FORCE_OBJECT);
echo $json;
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer but not entirely solve my problem. I may have arrays in deeper layers.
0

You can use the JSON_FORCE_OBJECT option:

$array = array(
    0 => 'Banana',
    1 => 'Minions',
    2 => array(
        5 => 'MariaOzawa',
        6 => 'YukiOsawa'
    )
);
$myJsonString = json_encode($MyArray, JSON_FORCE_OBJECT);
print_r($myJsonString);

Then you can see result like this:

{"0":"Banana","1":"Minions","2":{"5":"MariaOzawa","6":"YukiOsawa"}}

With this way, you can keep your array keys whatever how many layers is it into json_object

Hope this help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.