如何在php中将某些对象属性转换为json
我有一个php类,比方说:如何在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
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属性。