[英]PHP modify value of object property in an array of objects
I have a user model, with a profile_details column which holds a json_encoded object of the user profile information.我有一个用户 model,其 profile_details 列包含用户个人资料信息的 json_encoded object。 The object is as shown below
object如下图
$user->profile_details: {
'name' : 'Wayne',
'books' : [
{ id: 1, title : 'Rich Dad' , isbn: 9780},
{ id: 3, title : 'Business school' , isbn: 8891}
]
}
How do I modify the value of the 'id' property of the books array after retrieving the user model from the database.从数据库中检索用户 model 后,如何修改 books 数组的“id”属性的值。
Below is what I have tried.以下是我尝试过的。
$user =User::find(1);
$newBooks = array();
if($user) {
$profile_details_decoded = json_decode($user->profile_details) ;
foreach($profile_details_decoded->books as $book) {
$book->id = 28;
array_push($newBooks, $book);
}
$user->profile_details->books = $newBooks;
}
dd($user->profile_details->books);
I expected the $newBooks
array to replace the $user->profile_details->books
array.我希望
$newBooks
数组替换$user->profile_details->books
数组。
Please someone should kindly guide me.请有人指导我。 Thanks.
谢谢。
Since profile_details
hold json_encoded data, you have to work on the copy of the array and assign the array completely to the column.由于
profile_details
包含 json_encoded 数据,因此您必须处理数组的副本并将数组完全分配给列。
$profile_details_decoded = json_decode($user->profile_details);
$newBooks = [];
foreach($user->profile_details->books as $book) {
$book->id = 28; // whatever logic you want fpr changing id
$newBooks[] = $book;
}
$profile_details_decoded->books = $newBooks
$user->profile_details = $profile_details_decoded;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.