I have an array that looks like this:
[
[
"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",
]
]
I want to have an array with only the arrays where type equals "file" and extension equals "html"
This is what I have so far and works great for 1 filter only
$filter = ['file'];
$contents = array_filter($contents, function ($event) use ($filter) {
return in_array($event['type'], $filter);
});
If I try to put multiple values in the filter and in the in_array function it complains.
How can I use 2 filters?
You can do it like this:
$contents = array_filter($contents, function ($event) {
return isset($event['type']) &&
isset($event['extension']) &&
$event['type'] === 'file' &&
$event['extension'] === 'html';
});
You can simply get it like this:
$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)
you can try this
// 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;
});
Laravel style alternative:
https://laravel.com/docs/5.8/helpers#method-array-where
$filtered = Arr::where($array, function ($value, $key) {
return $value['type'] === 'file' && $value['extension'] === 'html';
});
you can try this way :
$contents = array_filter($contents, function ($event){
return $event['type']=='file' && $event['extension']=='html';
});
or
$filter=['file','html'];
$contents = array_filter($contents, function ($event) use ($filter) {
return $event['type']==$filter[0] && $event['extension']==$filter[1];
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.