【发布时间】:2013-03-30 20:07:12
【问题描述】:
所以目前我有以下两个数组:
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。
不确定这是否有意义?
【问题讨论】:
-
在 foreach 循环顶部添加一个变量
$state = true;,当您检测到错误时,将 $state 设置为 false。循环完成后,如果所有都为真,则 $state 为真,如果一个或多个为假,则为假。此外,如果最终 1 个错误结果等于错误返回,则您可能会在结果变为错误时立即中断循环.. -
这肯定行不通,因为它每次输出真假时都会输出真假?
-
另外,为什么不让 $allowedTypes = array('png','jpeg','jpg','zip','mov');那么你不需要运行explode。
-
你需要“真”和“假”吗?还是只是为了看看发生了什么?我想我错过了你需要的东西。
-
有点知道你从哪里来,但我需要它以相反的方式。我的新代码在下面作为答案。似乎工作。