php - PHP修改对象数组中对象属性的值
问题描述
我有一个用户模型,其中包含一个 profile_details 列,其中包含一个用户个人资料信息的 json_encoded 对象。对象如下图
$user->profile_details: {
'name' : 'Wayne',
'books' : [
{ id: 1, title : 'Rich Dad' , isbn: 9780},
{ id: 3, title : 'Business school' , isbn: 8891}
]
}
从数据库中检索用户模型后,如何修改 books 数组的“id”属性的值。
以下是我尝试过的。
$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);
我希望$newBooks
数组替换$user->profile_details->books
数组。
请有人指导我。谢谢。
解决方案
由于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;
推荐阅读
- java - Joda:使用奇怪的时区格式将字符串解析为 DateTime
- c# - 匹配 HTML 和 Javascript 文件中的文件路径
- r - 如何消除基础 R 条形图中的额外空间?
- css - 需要将 div 内的元素对齐到同一行
- javascript - 显示/隐藏具有多种可能性的列表元素
- visual-studio-code - 在 VSCode 中,如何选择带有 - 的整个单词?
- python - 使用 sqlite3 在 Python 中创建数据库
- django - Django 模板:在不同列表上组合 2 个循环
- opengl - 访问原语 id/index 顶点属于 glsl:vertex-shader
- hadoop - 如何使用 Java 将 zip 文件直接从 URL 传输到 HDFS?