title: Using json_encode on objects in PHP (regardless of scope)
body: <p>I'm trying to output lists of objects as json and would like to know if there's a way to make objects usable to <code>json_encode</code>?  The code I've got looks something like</p>
  
  <pre><code>$related = $user-&gt;getRelatedUsers();
  echo json_encode($related);
  </code></pre>
  
  <p>Right now, I'm just iterating through the array of users and individually exporting them into arrays for <code>json_encode</code> to turn into usable json for me.  I've already tried making the objects iterable, but <code>json_encode</code> just seems to skip them anyway.</p>
  
  <p><em>edit</em>: here's the var_dump();</p>
  
  <pre><code>php &gt; var_dump($a);
  object(RedBean_OODBBean)#14 (2) {
    ["properties":"RedBean_OODBBean":private]=&gt;
    array(11) {
      ["id"]=&gt;
      string(5) "17972"
      ["pk_UniversalID"]=&gt;
      string(5) "18830"
      ["UniversalIdentity"]=&gt;
      string(1) "1"
      ["UniversalUserName"]=&gt;
      string(9) "showforce"
      ["UniversalPassword"]=&gt;
      string(32) ""
      ["UniversalDomain"]=&gt;
      string(1) "0"
      ["UniversalCrunchBase"]=&gt;
      string(1) "0"
      ["isApproved"]=&gt;
      string(1) "0"
      ["accountHash"]=&gt;
      string(32) ""
      ["CurrentEvent"]=&gt;
      string(4) "1204"
      ["userType"]=&gt;
      string(7) "company"
    }
    ["__info":"RedBean_OODBBean":private]=&gt;
    array(4) {
      ["type"]=&gt;
      string(4) "user"
      ["sys"]=&gt;
      array(1) {
        ["idfield"]=&gt;
        string(2) "id"
      }
      ["tainted"]=&gt;
      bool(false)
      ["model"]=&gt;
      object(Model_User)#16 (1) {
        ["bean":protected]=&gt;
        *RECURSION*
      }
    }
  }
  </code></pre>
  
  <p>and here's what json_encode gives me:</p>
  
  <pre><code>php &gt; echo json_encode($a);
  {}
  </code></pre>
  
  <p>I ended up with just this:</p>
  
  <pre><code>    function json_encode_objs($item){   
          if(!is_array($item) &amp;&amp; !is_object($item)){   
              return json_encode($item);   
          }else{   
              $pieces = array();   
              foreach($item as $k=&gt;$v){   
                  $pieces[] = "\"$k\":".json_encode_objs($v);   
              }   
              return '{'.implode(',',$pieces).'}';   
          }   
      }   
  </code></pre>
  
  <p>It takes arrays full of those objects or just single instances and turns them into json - I use it instead of json_encode.  I'm sure there are places I could make it better, but I was hoping that json_encode would be able to detect when to iterate through an object based on its exposed interfaces.</p>