我将如何创建一个按值过滤二维数组的函数?
给定以下数组:
Array ( [0] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => CarEnquiry [status] => NEW [appointment] => 0 ) [1] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => CarEnquiry [status] => CALL1 [appointment] => 0 ) [2] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => Finance [status] => CALL2 [appointment] => 0 ) [3] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => Partex [status] => CALL3 [appointment] => 0 )
我将如何过滤数组以仅显示name键中包含特定值的那些数组?例如name = 'CarEnquiry'。
name
name = 'CarEnquiry'
结果输出为:
Array ( [0] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => CarEnquiry [status] => NEW [appointment] => 0 ) [1] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => CarEnquiry [status] => CALL1 [appointment] => 0 ) )
编辑
我忘了提及搜索值应该是可互换的-即name = 'CarEnquiry'或name = 'Finance'。
name = 'Finance'
将PHP的array_filter)函数与回调一起使用。
$new = array_filter($arr, function ($var) { return ($var['name'] == 'CarEnquiry'); });
编辑:如果需要可互换,则可以稍微修改代码:
$filterBy = 'CarEnquiry'; // or Finance etc. $new = array_filter($arr, function ($var) use ($filterBy) { return ($var['name'] == $filterBy); });