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

时间:2019-07-19 11:06:07

标签: php arrays laravel

我有一个看起来像这样的数组:

[
  [
    "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个过滤器?

5 个答案:

答案 0 :(得分:0)

您可以这样做:

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

答案 1 :(得分:0)

您可以像这样简单地获取它:

$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 :(得分:0)

您可以尝试

// 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 :(得分:0)

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

答案 4 :(得分:0)

您可以尝试这种方式:

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