rpayanm rpayanm - 1 month ago 5
JSON Question

Issues in json_encode

I have this array:

$array = [
"stored_fields" => ["id"],
"match_all" => []
];


I want:

{"stored_fields":["id"],"match_all":{}}


But, When I call:

echo json_encode($array);


I got:

{"stored_fields":["id"],"match_all":[]}


If I use:

echo json_encode($array, JSON_FORCE_OBJECT);


I got:

{"stored_fields":{"0":"id"},"match_all":{}}


What I can do?

Answer

There might be a better way, but you can just force an object:

$array = [
  "stored_fields" => ["id"], 
  "match_all" => (object)[]
];