【问题标题】:How to remove an array from a Multidimensional array by key if condition is met Php如果满足条件,如何通过键从多维数组中删除数组 Php
【发布时间】:2019-08-17 05:40:00
【问题描述】:

我有一个这样的数组

array:2 [▼
  "id_1553623907416" => array:2 [▼
    "id_title" => "About"
    "id_content" => """
      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      <p>Helllo world</p>
      </body>
      </html>
      """
  ]
  "id_1553623916174" => array:2 [▼
    "id_title" => "Education"
    "id_content" => """
      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      <p>hello data</p>
      </body>
      </html>
      """
  ]
]

如果名为 id_15536​​23907416 的数组在子数组键 id_title 中包含值 About,我需要能够删除它。 ID 是动态的,因此必须是动态的。

该数组存储在变量@output 中。

 @foreach ($output as $item)    
   @if($item["id_title"] == "About")
      //remove array 
   @else
     //do something else 
   @endif
@endforeach

【问题讨论】:

  • 您可以将数组转换为Collection 并使用filter() 函数:laravel.com/docs/5.8/collections#method-filter。如果开销太大,请在下面的答案中使用unset() 方法。
  • 我认为这不是一个好方法。看来您在刀片模板中?如果是这样 - 在 MVC 视图中转换数据是不好的做法。您唯一可以在视图中应用的内容就是跳过此项目并转到下一个。

标签: php if-statement laravel-5 foreach


【解决方案1】:

使用您现有的代码(我不知道 Laravel)只需公开 foreachunset 中的密钥:

 @foreach ($output as $key => $item)    
   @if($item["id_title"] == "About")
      unset($output[$key]); 
   @endif
@endforeach

如果只能有一个,则在unset 之后添加break;

或者你可以过滤掉它们:

$output = array_filter($output, function($v) { return $v['id_title'] != 'About'; });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多