4

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

1 Answer 1

2
  • 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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.