How to filter a two dimensional array by value
How would I create a function that filters a two dimensional array by value?
Given the following array :
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
)
How would I filter the array to only show those arrays that contain a specific value in the name
key? For example name = 'CarEnquiry'
.
The resulting output would be:
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
)
)
EDIT
I forgot to mention that the search value should be interchangeable - i.e. name = 'CarEnquiry'
or name = 'Finance'
.
Use PHP's array_filter function with a callback.
$new = array_filter($arr, function ($var) {
return ($var['name'] == 'CarEnquiry');
});
Edit: If it needs to be interchangeable, you can modify the code slightly:
$filterBy = 'CarEnquiry'; // or Finance etc.
$new = array_filter($arr, function ($var) use ($filterBy) {
return ($var['name'] == $filterBy);
});
<?php
function filter_array($array,$term){
$matches = array();
foreach($array as $a){
if($a['name'] == $term)
$matches[]=$a;
}
return $matches;
}
$new_array = filter_array($your_array,'CarEnquiry');
?>