简体   繁体   English

使用array_filter和foreach,错误

[英]With array_filter and foreach , error

I have a 2 arrays as 我有一个2阵列

 $check_string = array("www.salmat.", "www.webcentral.", "abpages.");

and

$files = array("http_www.salmat.com.au_.png", "http_www.webcentral.com.au_.png");

And now i want to check if value of each element in array $check_string matches with atleast part of a string of each element of array $files and if it does not match then i will echo respective values $check_string. 现在我想检查数组$check_string matches每个元素的值是否与数组$files的每个元素的字符串的至少部分$check_string matches ,如果它不匹配,那么我将回显各自的值$ check_string。

So i am doing with array_filter function 所以我正在使用array_filter函数

foreach ($check_string as $final_check) 
{
    function my_search($haystack) 
    {
        global $final_check;
        $needle = $final_check;
        return(strpos($haystack, $needle));
    }
    $matches[] = array_filter($files, 'my_search');
    if(empty($matches))
    {
       echo $final_check;
       echo "</br>";
    }
}

But with this code i get an error 但是这个代码我得到一个错误

Fatal error:  Cannot redeclare my_search() (previously declared in same file)

Can any one suggest any solution 可以任何人建议任何解决方案

i refereed this and this but cannot get through the solution Thankyou 我审阅这个这个 ,而是通过解决三江源不能得到

 function my_search($haystack) 
    {
        global $final_check;
        $needle = $final_check;
        return(strpos($haystack, $needle));
    }

That function needs to be defined outside the loop. 该函数需要在循环定义。 And you can just call it again and again in the loop. 你可以在循环中一次又一次地调用它。 Currently you are trying to redeclare it on every iteration of the loop. 目前,您正尝试在循环的每次迭代中重新声明它。

Not going to suggest further fixes to your code since it's logic is not very good. 不会建议进一步修复你的代码,因为它的逻辑不是很好。 You can try something like this 你可以尝试这样的事情

$check_string = array("www.salmat.", "www.webcentral.", "abpages.");
$files = array("http_www.salmat.com.au_.png", "http_www.webcentral.com.au_.png");

foreach($check_string as $check)
{
  $found=FALSE;
  foreach($files as $file)
  {
    if(stristr($file,$check)!==FALSE)
      $found=TRUE;
  }
  if(!$found)
    echo $check,"\n";
}

Fiddle 小提琴

Of course you can improve it and use less code but that gives you a direction. 当然,你可以改进它并使用更少的代码,但这会给你一个方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM