首页 > 解决方案 > 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数组。

请有人指导我。谢谢。

标签: phplaravel

解决方案


由于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;

推荐阅读