2017-04-13 25 views
0

我有一个函数返回mp3列表的质量。我想要返回HD值如果我到达数组中的最后一个元素,但我在foreach循环中遇到问题,则返回true。它总是返回true。如何在foreach循环中获得最高数字

代码

function funcName() { 
    foreach($dirs as $d) { 
     if (filesize($d) > 200) { 
      $qualities = substr(strrchr(basename($d), "-"), 1); 
      $qualities = preg_replace('/\\.[^.\\s]{3,4}$/', '', $qualities); 
      // This is where I check whether it is the last element or not. 
      $numItems = count($dirs); 
      $i = 0; 
      foreach($dirs as $key => $value) { 
       if (++$i === $numItems) { 
        $zaa = true; 
       } else { 
        $zaa = false; 
       } 
      } 
      $files[] = ["files" => basename($d), "qualities" => $qualities, "hd" => $zaa]; 
     } 
    } 
    return ($files); 
} 

我只是想回到$zaa = true如果我达到了最后一个元素。在我的代码中,它始终返回true

请问你能告诉我我失败的部分吗?

+0

将您的计数($ dirs)放在您的foreach循环之上,每迭代一次,您将重新计算数组/集合的大小。这是表现不是解决方案。 –

回答

1

我想这应该工作:

function funcName() { 

$numItems = count($dirs); 
$i = 0; 
foreach($dirs as $d) { 
$i++; 
    if (filesize($d) > 200) { 
     $qualities = substr(strrchr(basename($d), "-"), 1); 
     $qualities = preg_replace('/\\.[^.\\s]{3,4}$/', '', $qualities);   
     if ($i == $numItems) { 
      $zaa = true; 
     } else { 
      $zaa = false; 
     }    
     $files[] = ["files" => basename($d), "qualities" => $qualities, "hd" => $zaa]; 
    } 
} 
return ($files); 
} 
+0

告诉我它是否按预期工作 – NoOorZ24

+0

是的,这工作非常感谢你,我想出了另一种解决方案,但我会将你的问题标记为正确的谢谢!:) –

1

您不必循环$dirs再次,只是做这样的:

function funcName() { 
    $i = 1; 
    $numItems = count($dirs); 
    foreach($dirs as $d) { 
     $i++; 
     $zaa = $i === $numItems; 
     if (filesize($d) > 200) { 
      $qualities = substr(strrchr(basename($d), "-"), 1); 
      $qualities = preg_replace('/\\.[^.\\s]{3,4}$/', '', $qualities); 
      // This is where I check whether it is the last element or not. 
      $numItems = count($dirs); 

      $files[] = ["files" => basename($d), "qualities" => $qualities, "hd" => $zaa]; 
     } 
    } 
    return ($files); 
} 
+0

这并没有工作,仍然返回所有结果:( –

+0

@LunaticFnatic我编辑了我的答案。你不需要循环两次'$ dirs',实际上它不会工作。 – Alisson

+0

谢谢,我也赞成你的答案,它的工作原理,但我想出了另一种解决方案:) –

0

您可以通过以下条件改变你的病情。如果您的密钥从0开始,那么您需要(sizeof($ dirs) - 1)来获取总数组元素。

if(sizeof($dirs) == $key) 
+0

这仍然返回true所有的结果 –

0

使用for循环相反,如果你正在使用COUNT()和所有那些陈述它只是增加无用行代码,用于(){}会更短,更简单

+0

顺便说一句TRUE来自第一回路内部的secound循环,这是没有意义的,只是把这些线外,或者你是每次都在该循环中的最后一个项目,并收到真实 – NoOorZ24

+0

有没有更容易的解决方案检查最后一个元素没有第二个foreach或count()?如果可能的话,你可以给我一个forloop版本的例子吗?提前致谢! –

+0

我发布了新的答案,仍然使用foreach,只是因为我太懒惰了,我没有说你需要摆脱count(),你只是用它错了 – NoOorZ24

0

这两个答案是正确的,但我想出了这个解决方案似乎更快;

if ($d === end($dirs)) { 
    $zaa = true; 
} else { 
    $zaa = false; 
} 
相关问题