Creating a Function for Value-Based Filtering of Two-Dimensional Arrays
Filtering specific data from multi-dimensional arrays is a common task in programming. This task can be accomplished using various techniques, including PHP's array_filter function.
Function Creation
To create a function that filters a two-dimensional array by value, follow these steps:
Example Implementation
Consider the following array:
$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 ] ];
To filter this array for values containing 'CarEnquiry' in the 'name' key:
function filterArrayByName($arr) { return array_filter($arr, function($var) { return $var['name'] == 'CarEnquiry'; }); }
Customizable Filtering
To make the search value interchangeable, modify the callback function as follows:
function filterArrayByName($arr, $filterBy) { return array_filter($arr, function($var) use ($filterBy) { return $var['name'] == $filterBy; }); }
Now you can use the function to filter the array by any desired value in the 'name' key.
The above is the detailed content of How Can I Create a PHP Function to Filter a Two-Dimensional Array Based on Value?. For more information, please follow other related articles on the PHP Chinese website!