簡體   English   中英

刪除數組和數組Laravel中的值

[英]Delete value in array and in array Laravel

我有陣列

Product:[
     {
       content:'',
       tag:[
         {
           name:'a',
         },
         {
           name:'b'
         }
       ]
     }
]

我有價值x = 'a'

我需要刪除name == x數組product中的tag name == x

我使用了兩個foreach,一個foreach循環Product和一個foreach循環標記,然后檢查條件if(name == x)並刪除item

$tag = 'a'

foreach($blogs as $blog) {

    foreach(json_decode($blog->tag) as $detail_tag) {

        if($detail_tag == $tag) {

            delete($detail_tag);
        }
    }
}

但是,我的意思是功能有一些錯誤(我在紙上寫代碼,我不測試:()我的意思是沒有性能@@。謝謝

  • 您需要首先使用json_decode()函數將JSON對象轉換為數組。 此函數中的第二個參數設置為true ,以便將JSON轉換為關聯數組。
  • 然后,循環遍歷數組。 foreach您還需要訪問鍵,以便unset()值。
  • 然后,使用json_encode()函數將數組轉換回JSON對象。

嘗試:

$tag = 'a';

foreach($blogs as $blog) {

  // convert to array using json_decode() (second parameter to true)
  $blog_arr = json_decode($blog->tag, true);

  // Loop over the array accessing key as well
  foreach( $blog_arr as $key => $detail_tag){

      if ($detail_tag === $tag) {
          // unset the key
          unset($blog_arra[$key]);
      }

   // Convert back to JSON object
   $blog_tag_modified = json_encode($blog_arr);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM