json encode is not working with array of objects

后端 未结 5 1495
故里飘歌
故里飘歌 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:26

    As Ray says if your class properties are protected or private, these will not be jsoned.

    Since PHP 5.4 instead of using the commented toJson method, you have the ability to specify which data will be serialized implementing the JsonSerializable interface, so json_encode knows how to work on this.

    /* PHP >= 5.4 only */
    class Visits_Model_Visit implement JsonSerializable {
        public function jsonSerialize()
        {
            return array(
                 'day' => $this->day,
                 'date' => $this->date,
                 'target' => $this->target,
                 'id' => $this->id,
                 'status' => $this->status,
            );
        }
    }
    

提交回复
热议问题