0

I want to insert {"0":"1"} into a mysql database which I thought was straightforward!

I did this:

$arr = array('0' => '1');
echo json_encode($arr); 

But that gives ["1"]

however if I do this:

$arr = array('0' => '1',"b" =>"2");
echo json_encode($arr); 

I get this

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

Can someone help and explain what I need to do to get:

{"0":"1"} 

thanks

1
  • You need json_encode($arr, JSON_FORCE_OBJECT);
    – Priya
    Mar 21, 2019 at 18:20

2 Answers 2

1

You need to pass the JSON_FORCE_OBJECT as the second parameter to json_encode():

$arr = ['0' => '1'];
echo json_encode($arr, JSON_FORCE_OBJECT);

output:

{"0":"1"}

Demo

0

Use json_encode($arr, JSON_FORCE_OBJECT)

Not the answer you're looking for? Browse other questions tagged or ask your own question.