PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

Viewed 35140

I have a PHP data structure I want to JSON encode. It can contain a number of empty arrays, some of which need to be encoded as arrays and some of which need to be encoded as objects.

For instance, lets say I have this data structure:

$foo = array(
  "bar1" => array(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);

I would like to encode this into:

{
  "bar1": {},
  "bar2": []
}   

But if I use json_encode($foo, JSON_FORCE_OBJECT) I will get objects as:

{
  "bar1": {},
  "bar2": {}
}

And if I use json_encode($foo) I will get arrays as:

{
  "bar1": [],
  "bar2": []
}

Is there any way to encode the data (or define the arrays) so I get mixed arrays and objects?

3 Answers

Same answer, for PHP5.4+.

$foo = [
  "bar1" => (object)["",""],
  "bar2" => ["",""]
];

echo json_encode($foo);

Another simple examples, with something important to notice:

$icons = (object)["rain"=>[""], "sun"=>[""], "lightrain"=>[""]];
echo $icons->sun;
// 

$icons = (object)["rain"=>"", "sun"=>"", "lightrain"=>""];
echo $icons->sun;
// 
Related