筛选数组 $listMenu
Array
(
[0] => Array
(
[type] => 0
[min] => 0
)
[1] => Array
(
[type] => 1
[min] => 1
)
)
目标数组 $res
Array
(
[0] => Array
(
[id] => 183
[type] => 0
[min] => 0
)
[1] => Array
(
[id] => 184
[type] => 0
[min] => 1
)
[2] => Array
(
[id] => 185
[type] => 0
[min] => 2
)
[3] => Array
(
[id] => 186
[type] => 0
[min] => 3
)
[4] => Array
(
[id] => 187
[type] => 1
[min] => 0
)
[5] => Array
(
[id] => 188
[type] => 1
[min] => 1
)
[6] => Array
(
[id] => 189
[type] => 1
[min] => 2
)
[7] => Array
(
[id] => 190
[type] => 1
[min] => 3
)
[8] => Array
(
[id] => 191
[type] => 2
[min] => 0
)
[9] => Array
(
[id] => 192
[type] => 2
[min] => 1
)
[10] => Array
(
[id] => 193
[type] => 2
[min] => 2
)
[11] => Array
(
[id] => 194
[type] => 2
[min] => 3
)
[12] => Array
(
[id] => 195
[type] => 3
[min] => 0
)
[13] => Array
(
[id] => 196
[type] => 3
[min] => 1
)
[14] => Array
(
[id] => 197
[type] => 3
[min] => 2
)
[15] => Array
(
[id] => 198
[type] => 3
[min] => 3
)
)
思路,用array_filter() 函数 过滤
array_filter() 函数使用
function test_odd($var)
{
return($var & 1);
}
$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
PHP闭包 function() use(){}
闭包的语法很简单,需要注意的关键字就只有use,use意思是连接闭包和外界变量。
$a =function()use($b) {
}
代码
foreach ($listMenu as $key=>$val){
$dataArr[]=array_filter($res,function ($var)use ($val){
if($var['type']==$val['type']&&$var['min']==$val['min']) return true;
});
}
//数组降维处理
array_walk($dataArr, function(&$v) {$v = current($v);});
print_r($dataArr);
输出
Array
(
[0] => Array
(
[id] => 183
[type] => 0
[min] => 0
)
[1] => Array
(
[id] => 188
[type] => 1
[min] => 1
)
)
升级版
/**
*使用数组筛选
*
*/
static public function getMenuAll(){
$res=[]
//return self::reSort($result);
$item['pid'] = 0;
$result = self::screen($res,$item);
return $result;
}
/**
* 筛选数组方法
* @param $res
* @param $val
* @return array
*/
static public function screen($res,$val){
return array_filter($res,function ($var) use ($val){
if($var['type']==$val['type']&&$var['min']==$val['min']) return true;
});
}