JSON objects in PHP

PHP is easy. You don’t have to know type of variable, before you use it. But sometimes it’s very problematic especially when we are dealing with JSON.

Here is an example:

{
  "page-size":50,
  "channel":"buy",
  "sort":{}, 
  "filters":{
    "surrounding-suburbs":true
  },
  "localities":[{
     "subdivision":"DO",
     "locality":"Unknown"}
]}

It’s a very odd combination of arrays and objects. To build this type of object we have to typecast some of the variables:

  $builder = [
            'page-size' => 50,
            'channel' => 'buy',
            'sort'  => (object)[],
            'filters' => (object)['surrounding-suburbs' => true],
            'localities' => [(object)['subdivision' => 'DO', 'locality' => 'Unknown']]
          ];

  print_r(json_encode($builder));