【问题标题】:Delete value in array and in array Laravel删除数组和数组 Laravel 中的值
【发布时间】:2018-10-07 15:29:58
【问题描述】:

我有数组

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

我有价值x = 'a'

我需要删除数组producttag 中的名称name == x

我使用了两个foreach,一个foreach循环Product和一个foreach循环标签,然后检查条件if(name == x)并删除项目

代码

$tag = 'a'

foreach($blogs as $blog) {

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

        if($detail_tag == $tag) {

            delete($detail_tag);
        }
    }
}

但是,我的意思是函数有一些错误(我在纸上编写代码并且我不测试:()我的意思是它没有性能@@。谢谢

【问题讨论】:

    标签: php laravel


    【解决方案1】:
    • 您需要先使用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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2019-09-04
      相关资源
      最近更新 更多