如何在数组中搜索?

时间:2018-10-06 09:43:37

标签: php arrays

我有代码:

$acceptFormat = array(
  'jpg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
  throw new RuntimeException('Invalid file format.');
}

$mime = mime_content_type($_FILES['file']['tmp_name'][$i]);
if ($mime != "image/jpeg" && $mime != "image/jpg" && $mime != "image/png") {
   throw new RuntimeException('Invalid mime format.');
}

我有一个$acceptFormat数组,其中包含允许的文件格式和两个ify:

  1. if ($ mime! = "Image / jpeg" && $ mime! = "Image / jpg" && $ mime! = "Image / png")

  2. if ($ ext! = "Jpg" && $ ext! = "Jpeg" && $ ext! = "Png")

如果要根据acceptFormat数组检查扩展名和mime类型,是否可以对它进行某种修改?

3 个答案:

答案 0 :(得分:1)

尝试使用in_array()array_keys()来获取文件扩展名,并使用array_values()来获取 mime 值。让我们看看,

<?php

$acceptFormat = array(
  'jpg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

$ext ='jpg'; // demo value

if (!in_array($ext,array_keys($acceptFormat))) {
  throw new RuntimeException('Invalid file format.');
}

$mime = 'video/mkv'; // demo value

if (!in_array($mime,array_values($acceptFormat))) {
   throw new RuntimeException('Invalid mime format.');
}
?>

演示: https://3v4l.org/aNdMM

答案 1 :(得分:0)

$filename = "path.ext";

$acceptFormat = array(
  'jpeg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

if(! array_key_exists($ext, $acceptFormat)) throw new RuntimeException('Invalid file format.');

$mime = mime_content_type($_FILES['file']['tmp_name'][$i]);
if(! in_array($mime, $acceptFormat)) throw new RuntimeException('Invalid mime format.');

您需要array_key_exists来搜索键。当然,您需要pathinfo来获取扩展名。

接下来,您需要in_array来搜索mime类型的值。

答案 2 :(得分:0)

这应该有效。

 $acceptFormat = array(
    'jpeg'  => 'image/jpeg',
    'jpg'   => 'image/jpg',
    'png'   => 'image/png'
);

$isValid = false;

foreach ($acceptFormat as $extension => $mimeType) {
    if ($ext === $extension && $mime === $mimeType) {
        $isValid = true;
        break;
    }
}

if (!$isValid) {
    throw new RuntimeException('Invalid extension/mime type.');
}

// All is good..