简体   繁体   中英

Delete value in array and in array Laravel

I have array

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

And i have value x = 'a'

I need delete name in tag in array product where name == x

I used two foreach, one foreach loop Product and one foreach loop tag, then checking condition if(name == x) and delete item

Code

$tag = 'a'

foreach($blogs as $blog) {

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

        if($detail_tag == $tag) {

            delete($detail_tag);
        }
    }
}

However, I mean function have some error ( I write code on paper and I don't test :( ) and I mean it no performance @@. Thanks

  • You need to first convert the JSON object to array using json_decode() function. Second parameter in this function is set to true , in order to convert the JSON into associative array.
  • Then, loop over the array. In foreach you need to access key as well, in order to unset() the value.
  • Then, convert the array back to JSON object using json_encode() function.

Try:

$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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM