Efficiently Filtering a Two-Dimensional Array by Value in PHP
In PHP programming, efficiently filtering a two-dimensional array by a specific value can be achieved using the versatile array_filter function in combination with a callback.
Simple Filtering by a Single Value
To filter an array by a specific value in a key, we can use the following syntax:
$new = array_filter($arr, function ($var) { return ($var['name'] == 'CarEnquiry'); });
Here, $arr is the input array, and the callback function checks if the name key in each sub-array matches the target value. The resulting $new array contains only the sub-arrays where name equals 'CarEnquiry'.
Interchangeable Filtering for Multiple Values
If the target value may vary, we can enhance the callback function to handle interchangeable filtering:
$filterBy = 'CarEnquiry'; // or Finance etc. $new = array_filter($arr, function ($var) use ($filterBy) { return ($var['name'] == $filterBy); });
The use keyword in the callback function allows us to access the $filterBy variable, which can be modified to specify different target values, allowing dynamic filtering.
Example Usage
Consider the following array as an example:
$arr = [ [ 'interval' => '2014-10-26', 'leads' => 0, 'name' => 'CarEnquiry', 'status' => 'NEW', 'appointment' => 0 ], [ 'interval' => '2014-10-26', 'leads' => 0, 'name' => 'CarEnquiry', 'status' => 'CALL1', 'appointment' => 0 ], [ 'interval' => '2014-10-26', 'leads' => 0, 'name' => 'Finance', 'status' => 'CALL2', 'appointment' => 0 ], [ 'interval' => '2014-10-26', 'leads' => 0, 'name' => 'Partex', 'status' => 'CALL3', 'appointment' => 0 ] ];
Filtering $arr to include only entries where name equals 'CarEnquiry' results in:
$filtered = array_filter($arr, function ($var) { return ($var['name'] == 'CarEnquiry'); });
The resulting $filtered array will contain:
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 ) )
The above is the detailed content of How can I efficiently filter a two-dimensional array in PHP by a specific value?. For more information, please follow other related articles on the PHP Chinese website!