json encode is not working with array of objects

后端 未结 5 1510
故里飘歌
故里飘歌 2020-12-31 04:06

I want to convert array of objects to json encoding, I make like this

$allVisits = $mapper->getAllVisits($year, $month);
echo json_encode($allVisits);
         


        
5条回答
  •  醉话见心
    2020-12-31 04:33

    By default, json_encode() only serializes public properties of an object. Making all properties you want serialized public is NOT the solution! PHP 5.4 and later has the JsonSerializable interface, but I propose a straightforward solution for earlier versions of PHP.

    Since JsonSerializable is only part of PHP 5.4 and later, create it yourself.

    if (!interface_exists('JsonSerializable')) {
       interface JsonSerializable {
          public function jsonSerialize();
       }
    }
    

    That wasn't so hard, was it? Now we can implement JsonSerializable without worrying about what version of PHP we are using!

    class Visits_Model_Visit implements JsonSerializable {
        ...
        // Only put properties here that you want serialized.
        public function jsonSerialize() {
            return Array(
               'day'    => $this->day,
               'date'   => $this->date,
               'target' => $this->target,
               'id'     => $this->id,
               'status' => $this->status,
               'obj'    => $this->obj->jsonSerialize(), // example for other objects
               'time'   => $this->time
            );
        }
        ...
    }
    

    Now you can just call jsonSerialize() to get an associative array that you can encode with json_encode().

        ...
        $entry = new Visits_Model_Visit();
        $entry->setId($row->visit_id)
              ->setDay($row->day)
              ->setDate($row->date)
              ->setTarget($row->target)
              ->setStatus($row->visit_status)
              ->setTime($row->visit_time);
    
        $visitsEntries[] = $entry->jsonSerialize();
        ...
    

    You may then call json_encode($visitsEntries) to get your desired result.

    [
       {
          "day":"sunday",
          "date":"2012-03-06",
          "target":"\u0634\u0633\u064a",
          "id":1,
          "status":0,
          "time":"12:00:00"
       },
       {
          "day":"sunday",
          "date":"2012-03-06",
          "target":"clinnics",
          "id":4,
          "status":0,
          "time":"00:00:00"
       },
       ...
    ]
    

提交回复
热议问题