PHP-本机函数以通过其索引获取数组的所有值



我需要知道是否有一个本机PHP函数可以使我获取数组的所有值,并指定要获取的索引,而无需循环,例如

我在功能中有此数组列表:

function get_mime($index)
{
    $data = array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
        'zip' => 'application/x-compressed',
        'doc' => 'application/msword',
        'dot' => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
        'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
        'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
        'xls' => 'application/vnd.ms-excel',
        'xlt' => 'application/vnd.ms-excel',
        'xla' => 'application/vnd.ms-excel',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
        'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
        'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
        'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
        'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
        'ppt' => 'application/vnd.ms-powerpoint',
        'pot' => 'application/vnd.ms-powerpoint',
        'pps' => 'application/vnd.ms-powerpoint',
        'ppa' => 'application/vnd.ms-powerpoint',
        'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
        'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
        'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
        'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
        'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
        'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'
    );
    return $data;
}

我需要调用此功能:

get_mime(array('jpg', 'png', 'gif'));

并返回带有值的数组:

array('image/jpeg', 'image/png', 'image/gif')
$res = array_intersect_key(array_flip(['jpg', 'png', 'gif']), $data);
function get_mime($index)
{
    $data = array(
       //...
    );
    return array_values(
        array_intersect_key(
            $data, array_combine(
                $index, array_fill(
                    0, count($index)
                )
            )
        )
    );
}

从技术上讲,这只是php循环的天然函数。但是,当然,在引擎盖下,PHP将在两个阵列中循环几次。

我通常不建议使用此解决方案。通常,简单的for循环更有效,更可读性。

最新更新