Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中将某些对象属性转换为json_Php_Arrays_Json - Fatal编程技术网

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

如何在php中将某些对象属性转换为json,php,arrays,json,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($studen

我有一个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属性


是否有一种方法可以轻松实现这一点?

您的对象需要实现
JsonSerializable
接口

class StudentDisplay implements JsonSerializable {
然后添加您想要在
jsonSerialize
方法中返回的任何内容

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

$result=json_encode($object->getStudent_id())???@Abracadver,这不起作用,因为它是某些属性。我需要打印的不仅仅是一个属性。当我在对象上调用json encode时,某些属性。如果有一种方法可以将这些属性标记为非json可序列化的,例如..你不是这么说的:我只想显示student_id属性。