Laravel PHP通过多个键值过滤多维数组

Posted

技术标签:

【中文标题】Laravel PHP通过多个键值过滤多维数组【英文标题】:Laravel PHP filter multidimensional array by multiple key values 【发布时间】:2019-11-28 08:57:11 【问题描述】:

我有一个如下所示的数组:

[
  [
    "type" => "dir",
    "path" => "vendor/test/test",
    "dirname" => "vendor/test",
    "basename" => "test",
    "filename" => "test",
  ],
  [
    "type" => "file",
    "path" => "vendor/test/test.html",
    "visibility" => "public",
    "size" => 0,
    "dirname" => "vendor/test",
    "basename" => "test.html",
    "extension" => "html",
    "filename" => "test",
  ],
   [
    "type" => "file",
    "path" => "vendor/test/test2.html",
    "visibility" => "public",
    "size" => 0,
    "dirname" => "vendor/test",
    "basename" => "test2.html",
    "extension" => "txt",
    "filename" => "test2",
  ]
]

我想要一个数组,其中只有类型等于“文件”且扩展名等于“html”的数组

这是我目前所拥有的,仅适用于 1 个过滤器

$filter = ['file'];
$contents = array_filter($contents, function ($event) use ($filter) 
    return in_array($event['type'], $filter);
);

如果我尝试在过滤器和 in_array 函数中放置多个值,它会报错。

如何使用 2 个过滤器?

【问题讨论】:

【参考方案1】:

你可以像这样简单地得到它:

$result = [];
foreach ($contents as $item) 
    if (in_array('type', $item)) 
        if ($item['type'] === 'file') 
            if (in_array('extension', $item)) 
                if ($item['extension'] === 'html') 
                    $result[] = $item;
                
            
        
    

// dd($result)

【讨论】:

【参考方案2】:

你可以试试这个

// setting a filter for each key we want
$filters = ['extension'=>['html'],'type'=>['file','dir']];
$contents = array_filter($contents, function ($event) use ($filters) 
    // checking for each filter inside the associative array
    foreach($filters as $key => $filter)
       // assuming $key is type and $filter is file,dir 
       // if type isn't file or dir it'll remove the event from the contents
       if(!in_array($event[$key], $filter)
         return false;
       
    
    return true;
);

【讨论】:

【参考方案3】:

你可以这样做:

$contents = array_filter($contents, function ($event) 
    return isset($event['type']) &&
        isset($event['extension']) &&
        $event['type'] === 'file' && 
        $event['extension'] === 'html';
);

【讨论】:

【参考方案4】:

Laravel 样式替代:

https://laravel.com/docs/5.8/helpers#method-array-where

$filtered = Arr::where($array, function ($value, $key) 
    return $value['type'] === 'file' && $value['extension'] === 'html';
);

【讨论】:

【参考方案5】:

你可以试试这个方法:

$contents = array_filter($contents, function ($event)
    return $event['type']=='file' && $event['extension']=='html';
);

   $filter=['file','html'];
   $contents = array_filter($contents, function ($event) use ($filter) 
        return $event['type']==$filter[0] && $event['extension']==$filter[1];
  );

【讨论】:

以上是关于Laravel PHP通过多个键值过滤多维数组的主要内容,如果未能解决你的问题,请参考以下文章

通过(例如:标题或描述)值中的关键字过滤多维数组(PHP)

使用带有 sql 的键值对搜索 php 多维关联数组,例如 '%LIKE%' 构造

如何在php中通过键值合并两个多维数组?

php多维数组通过多个键和值搜索

Laravel 5.7 中的 php 多维数组循环问题

使用PHP检查多维数组中是否存在键值