多维数组过滤器类似于mysql LIKE

时间:2015-04-17 18:36:03

标签: php

这是我的阵列:

$database[0] = array("country"=>"UK", "product" => "pen423", "company" => "ht789"); 
$database[1] = array("country"=>"USA", "product" => "pen123", "company" => "hi789"); 
$database[2] = array("country"=>"UK", "product" => "pen423", "company" => "ht789");
 $database[3] = array("country"=>"UK", "product" => "pen423", "company" => "ht789");
 $database[4] = array("country"=>"UK", "product" => "pen4023", "company" => "hi7789"); 

我想要获得的输出数组:" Country" ="英国"和"公司"喜欢" ht%"

因此,输出将是:

$database[0] = array("country"=>"UK", "product" => "pen423", "company" => "ht789"); 
$database[2] = array("country"=>"UK", "product" => "pen423", "company" => "ht789");
 $database[3] = array("country"=>"UK", "product" => "pen423", "company" => "ht789");

是否有可能像sql语句和没有使用循环?

2 个答案:

答案 0 :(得分:2)

您可以使用array_filter()。它接受一个回调,您可以在其中添加自定义逻辑到过滤结果集。

使用strpos()substr()之类的字符串函数应该非常简单。

答案 1 :(得分:2)

使用array_filter

function filterfunction($value) 
{

    if(strcmp($value['country'],"UK")!=0
      return false;
    if(strcmp(substr($value['company'],0,2),"ht")==0)
      return true;
    return false; 
}

$filterarr = array_filter($database, "filterfunction");