简体   繁体   English

删除数组和数组Laravel中的值

[英]Delete value in array and in array Laravel

I have array 我有阵列

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

And i have value x = 'a' 我有价值x = 'a'

I need delete name in tag in array product where name == x 我需要删除name == x数组product中的tag name == x

I used two foreach, one foreach loop Product and one foreach loop tag, then checking condition if(name == x) and delete item 我使用了两个foreach,一个foreach循环Product和一个foreach循环标记,然后检查条件if(name == x)并删除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. 您需要首先使用json_decode()函数将JSON对象转换为数组。 Second parameter in this function is set to true , in order to convert the JSON into associative array. 此函数中的第二个参数设置为true ,以便将JSON转换为关联数组。
  • Then, loop over the array. 然后,循环遍历数组。 In foreach you need to access key as well, in order to unset() the value. foreach您还需要访问键,以便unset()值。
  • Then, convert the array back to JSON object using json_encode() function. 然后,使用json_encode()函数将数组转换回JSON对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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