PHP数组模糊查找,用来模糊搜索,非常好用


<?php
var_dump(search('广'));

function search($name) {
    
    $a=array(
    '0' => array('id'=>1,'pid'=>0,'name'=>'北京市'),
    '1' => array('id'=>2,'pid'=>0,'name'=>'上海市'),
    '2' => array('id'=>3,'pid'=>1,'name'=>'广州省'),
    '3' => array('id'=>4,'pid'=>2,'name'=>'云南'),
    '4' => array('id'=>5,'pid'=>1,'name'=>'黑龙江'),
    '5' => array('id'=>6,'pid'=>3,'name'=>'广西'),
    '6' => array('id'=>7,'pid'=>4,'name'=>'海南'),
    '7' => array('id'=>8,'pid'=>5,'name'=>'山东'),
    '8' => array('id'=>9,'pid'=>7,'name'=>'吉林'),
    );
    
    $arr=$result=array();
    
    foreach ($a as $key => $value) {
        foreach ($value as $valu) {
            if(strstr($valu, $name) !== false)
            { 
            array_push($arr, $key);
            } 
        } 
    }
    foreach ($arr as $key => $value) {
        if(array_key_exists($value,$a)){
            array_push($result, $a[$value]);
        }
    }
    return $result; 
}
?>

结果:

array(2) { [0]=> array(3) { ["id"]=> int(3) ["pid"]=> int(1) ["name"]=> string(9) "广州省" } [1]=> array(3) { ["id"]=> int(6) ["pid"]=> string(1) "3" ["name"]=> string(6) "广西" } }