数组搜索不适用于max($ array),但在定义时有效

时间:2017-03-02 16:06:47

标签: php arrays

我有两个数组$yvalues$xyvalues

此代码返回 $matches的空集。

$a= max($yvalues);// equals 200
function my_search($haystack) {
    global $a;

$needle=$a;

return(strpos($haystack, $needle)); 
} 


$matches = array_filter($xyvalues, 'my_search');
print_r($matches);    

此代码有效

 $a= max($yvalues);// equals 200
function my_search($haystack) {
//      global $a;

$needle='200';

return(strpos($haystack, $needle)); 
} 


$matches = array_filter($xyvalues, 'my_search');
print_r($matches);    

在我的试用代码中我的工作原理就是为什么我要求帮助。

$b= array('11','20','23','14','23');
$c =array('20,12','13,12','200,23','100,23');
$bmax = max($b);
//echo $bmax ."<BR>";
function my_search($haystack) {
    global $bmax;

    $needle =$bmax;

    return(strpos($haystack, $needle)); 
}

$matches = array_filter($c, 'my_search');
print_r($matches);
$tst = key($matches);

1 个答案:

答案 0 :(得分:2)

好的,你可以这个

<?php    
#WORKING
$yvalues= array('11','20','23','14','23');
$xyvalues =array('20,12','13,12','200,23','100,23');
global $a;
$a = (string)max($yvalues);// equals 200
function my_search2($haystack) {
    global $a;
    $needle=(string)$a;
    return (bool)(strpos($haystack, $needle)!==false);
}
$matches = array_filter($xyvalues, 'my_search2');
print_r($matches);

#MODERN
print_r(array_filter($xyvalues, function($haystack) use ($yvalues){
    $needle = (string)max($yvalues);
    return (bool)(strpos($haystack, $needle)!==false);    
}));

结果:Array ( [2] => 200,23 [3] => 100,23 )

点数:

  • 如果你从$ needle中移除(string)它将不再起作用
  

如果needle不是字符串,则将其转换为整数并应用为字符的序数值

  • 如果您想首先保存生成全局var do global $a;

: - )