PHP foreach - 从多维数组搜索匹配

时间:2012-03-09 14:40:32

标签: php search multidimensional-array foreach match

我有一个数组

    $Cat[0]['name']     = "garfield 1";
$Cat[0]['color']    = "brown";
$Cat[0]['weight']   = "15";
$Cat[0]['age']      = "3";

    $Cat[1]['name']     = "garfield 2";
$Cat[1]['color']    = "brown";
$Cat[1]['weight']   = "15";
$Cat[1]['age']      = "3";

搜索词“gar”应该返回两只猫的数据。 并搜索单词“garfield 1”仅返回cat [0]

的数据

2 个答案:

答案 0 :(得分:1)

查看array_filter功能

答案 1 :(得分:0)

$garCats = array_filter($Cat, function($catDetails) { 
                                  return (strpos($catDetails['name'],'gar') !== FALSE); 
                              } 
                       );

修改

$searchString = 'gar';
$garCats = array_filter($Cat, function($catDetails) use($searchString) { 
                                  return (strpos($catDetails['name'],$searchString) !== FALSE); 
                              } 
                       );