2

所以目前我有以下两个数组:

Array ( [0] => image/jpeg [1] => image/png [2] => image/psd ) 
Array ( [0] => png [1] => jpeg [2] => jpg [3] => zip [4] => mov ) 

顶部数组是正在转发的 $_GET 数据,它们是上传的文件类型。第二个数组是允许的文件类型的逗号列表。基本上,我想要实现的是检查数组中的每个项目是否是允许的文件类型,如果不是则返回错误消息。

我的代码:

$fileTypes = $_GET['data']; // Get the JSON file types

$fileTypes = json_decode($fileTypes); // Decode the data

$allowedTypes = "png,jpeg,jpg,zip,mov"; // List of allowed file types
$allowedTypes = explode(",", $allowedTypes); // Explode the list to an array

// For each file type in the array
foreach ($fileTypes as $fileType) {

foreach($allowedTypes as $allowedType) { 

$pos = strpos($fileType, $allowedType); // Check if the allowed type is contained in the file type

if($pos == FALSE) { echo "False"; } else { echo "True"; }

}

现在的问题是,这将返回以下内容:

False, True, False, False, False (Overall will still equate to False, even though it had a true)
True, False, False, False, False (Overall will still equate to False, even though it had a true)
False, False, False, False, False (Overall will equate to false which it should as it has no trues)

现在正如您所看到的,当状态为真和假时,代码正在运行,但我需要对其进行整体评估。因此,如果每一行都有一个 true in,那么整体状态为 true,但是如果其中一行,如最后一行包含所有 false,则整体条件变为 false。

不确定这是否有意义?

4

3 回答 3

2

这似乎适用于 PENDO 的建议。

// For each file type in the array
$state = TRUE;

foreach ($fileTypes as $fileType) {

foreach($allowedTypes as $allowedType) { 

$pos = strpos($fileType, $allowedType); // Check if the allowed type is contained in the file type

if($pos === FALSE) { $state = FALSE; } else { $state = TRUE; break; }

}

}

echo $state;
于 2013-03-30T20:17:37.890 回答
1

零也是假的,因此,如果 strpos 在位置零找到字符串,它将是假的:尝试使用相同的运算符 ===

if($pos === FALSE) 
于 2013-03-30T20:13:46.030 回答
0
function trueOrFalse($fileTypes, $allowedTypes)
{
  foreach($fileTypes as $fileType) {
    foreach($allowedTypes as $allowedType) {

      $pos = strpos($fileType, $allowedType);
      if($pos == FALSE) return false;
    }
  }
  return true;
}

也许这有帮助。一旦检测到错误的 $pos,函数就会停止并返回 false。否则,它将执行该函数直到结束,如果所有 $pos 检查为真,则返回真。

于 2013-03-30T20:11:37.170 回答