找到第一个出现的包含搜索值的数组行并返回第一级键

问题描述 投票:0回答:2

我有以下数组:

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;
}
php arrays multidimensional-array filter
2个回答
1
投票

如果我明白你正在寻找这样的东西

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

0
投票

使用 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)
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.