我有以下数组:
Array
(
[documents] => Array
(
[0] => application/pdf
[1] => application/x-pdf
)
[images] => Array
(
[0] => image/cgm
[1] => image/g3fax
)
[videos] => Array
(
[0] => video/dl
[1] => video/fli
[2] => video/gl
[3] => video/mpeg
)
我有几个表,分别称为文档、图像、视频。所以我想做的是查看文件应该放在哪个数据库中。
array_search()
做到这一点,但没有成功。之后我发现了一个功能,我尝试了也没有运气。
function array_search_multi( $value, array $array ) {
foreach( $array as $key => $val ) {
if( is_array( $val ) ) {
array_search_multi($value, $val); // Recursive in case array is deeper
} else {
if( $val === $value ) {
return $key;
}
}
}
return false;
}
我希望有人能帮助我
如果我明白你正在寻找这样的东西
function find($mimeType) {
$array = [
'documents' => ['application/pdf','application/x-pdf'],
'images' => ['image/cgm','image/g3fax'],
'videos' => ['video/dl','video/fli','video/gl','video/mpeg'],
];
$table = null;
foreach ($array as $type => $values) {
$table = $type;
if ( in_array ($mimeType, $values) ) break;
}
return $table;
}
$sample = 'image/g3fax';
echo find($sample);
使用 PHP8.4 的
array_find_key()
和 in_array()
查找第一个出现的匹配项并返回第一级密钥。 演示
$array = [
'documents' => ['application/pdf','application/x-pdf'],
'images' => ['image/cgm','image/g3fax'],
'videos' => ['video/dl','video/fli','video/gl','video/mpeg'],
];
$find = 'image/g3fax';
var_export(
array_find_key(
$array,
fn($row) => in_array($find, $row)
)
);