json 编码不适用于对象数组

2022-08-30 20:46:07

我想将对象数组转换为json编码,我像这样

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

这是getAllVisists方法

 function getAllVisits($year, $month) {
    $where = array(
        'year = ?' => $year,
        'month = ?' => $month
    );
     $resultSet = $this->getDbTable()->fetchAll( $where);
    $visitsEntries = array();
    foreach ($resultSet as $row) {

        $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;
    }
    return $visitsEntries;
}

当我回显$allVisits的大小时,它会返回正确的记录数,但在js中,值被接收为空,如下所示[{},{},{},{},{}]

编辑

当我print_r($allVisists)brfore编码它时,它会返回

Array
(
    [0] => Visits_Model_Visit Object
        (
            [day:private] => sunday
            [date:private] => 2012-03-06
            [target:private] => شسي
            [id:private] => 1
            [status:private] => 0
            [time:private] => 12:00:00
        )

    [1] => Visits_Model_Visit Object
        (
            [day:private] => sunday
            [date:private] => 2012-03-06
            [target:private] => clinnics
            [id:private] => 4
            [status:private] => 0
            [time:private] => 00:00:00
        )

    [2] => Visits_Model_Visit Object
        (
            [day:private] => Tuesday
            [date:private] => 2012-03-06
            [target:private] => clinnics
            [id:private] => 5
            [status:private] => 0
            [time:private] => 00:00:00
        )

    [3] => Visits_Model_Visit Object
        (
            [day:private] => Wednesday
            [date:private] => 2012-03-28
            [target:private] => ??????? ???????
            [id:private] => 7
            [status:private] => 0
            [time:private] => 12:00:00
        )

)

答案 1

您正在对没有任何公共成员的对象使用json_encode。 只在它能“看到”的成员上工作,这就是为什么它们是空的。json_encode

从 PHP 5.4 开始,您可以使用 JsonSerializable 接口来控制将为其提供哪些数据,例如:json_encode

class Visits_Model_Visit implements JsonSerializable {
    ...
    public function jsonSerialize() {
        return (object) get_object_vars($this);
    }
    ...
}

如果您低于 5.4,您还可以实现该函数,而无需从接口扩展,然后手动分配正确的值:

$visitsEntries[] = $entry->jsonSerialize();

希望这有帮助。


答案 2

正如Ray所说,如果你的类属性是受保护的或私有的,这些属性将不会被 json 化。

由于 PHP 5.4 而不是使用 commented toJson 方法,因此您可以指定哪些数据将通过实现 JsonSerializable 接口进行序列化,因此json_encode知道如何处理这个问题。

/* 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,
        );
    }
}

推荐