如何在php中将某些对象属性转换为json

时间:2018-06-05 17:47:46

标签: php arrays json

我有一个php类,让我们说:

class StudentDisplay{
private $student_id;
private $student_display;

function getStudent_id() {
    return $this->student_id;
}

function getStudent_display() {
    return $this->student_display;
}

function setStudent_id($student_id) {
    $this->student_id = $student_id;
}

function setStudent_display($student_display) {
    $this->student_display = $student_display;
}

}  但是当我对这个对象进行json编码时,我只想显示student_id属性。

有没有办法可以轻松解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的对象需要实现JsonSerializable接口。

class StudentDisplay implements JsonSerializable {

然后在jsonSerialize方法中添加您想要返回的内容。

public function jsonSerialize()
{
    return [
        'student_id' => $this->student_id,
    ];
}

http://php.net/manual/en/class.jsonserializable.php

相关问题