我遇到了同样的问题,并尝试了其他 2 个答案。两者都不是很顺利。
-
$object = (array) $object; 在我的密钥中添加了很多额外的文本
名字。
- 序列化程序没有使用我的
active 属性,因为它前面没有is,而是boolean。它还改变了我的数据和数据本身的顺序。
所以我在我的实体中创建了一个新函数:
/**
* Converts and returns current user object to an array.
*
* @param $ignores | requires to be an array with string values matching the user object its private property names.
*/
public function convertToArray(array $ignores = [])
{
$user = [
'id' => $this->id,
'username' => $this->username,
'roles' => $this->roles,
'password' => $this->password,
'email' => $this->email,
'amount_of_contracts' => $this->amount_of_contracts,
'contract_start_date' => $this->contract_start_date,
'contract_end_date' => $this->contract_end_date,
'contract_hours' => $this->contract_hours,
'holiday_hours' => $this->holiday_hours,
'created_at' => $this->created_at,
'created_by' => $this->created_by,
'active' => $this->active,
];
// Remove key/value if its in the ignores list.
for ($i = 0; $i < count($ignores); $i++) {
if (array_key_exists($ignores[$i], $user)) {
unset($user[$ignores[$i]]);
}
}
return $user;
}
我基本上将我所有的属性都添加到了新的$user 数组中,并创建了一个额外的$ignores 变量,以确保可以忽略属性(以防您不想要所有属性)。
您可以在控制器中使用它,如下所示:
$user = new User();
// Set user data...
// ID and password are being ignored.
$user = $user->convertToArray(["id", "password"]);