二维数组之根据键值查询是否存在
业务需求:
给定一个二维数组,根据二维数组中的某个特定的键值以及想要查询的值,查询其是否存在,存在则返回查询到的数组,不存在则返回空数组,例如以下代码,想要查询出userId值为5的个数
代码:
$lists = [ [ 'catid' => 2, 'catdir' => 'notice', ], [ 'catid' => 5, 'catdir' => 'subject', ], [ 'catid' => 6, 'catdir' => 'news' ] ]; $catid = 5; $result = array_filter($lists, function($t) use ($catid) { return $t['catid'] == $catid; }); print_r($result);
执行结果:
[ 1 => [ 'catid' => 5, 'catdir' => 'subject' ] ]