Home >Backend Development >PHP Tutorial >How Can I Filter a Two-Dimensional Array in PHP Based on a Specific Key\'s Value?

How Can I Filter a Two-Dimensional Array in PHP Based on a Specific Key\'s Value?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 10:55:11163browse

How Can I Filter a Two-Dimensional Array in PHP Based on a Specific Key's Value?

Filtering a Two-Dimensional Array by Specific Value

Filtering a multidimensional array by a specific value can be accomplished through various programming techniques. In PHP, the array_filter function provides a convenient method for achieving this.

Filtering a Two-Dimensional Array by a Specific Key Value

To filter a two-dimensional array by a specific value, one can use the array_filter function along with a callback function. The callback function should evaluate each element of the array and return true if it meets the desired criteria.

For instance, consider the given array where we want to filter by the 'name' key with a value of 'CarEnquiry':

$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
    ]
];

The following code snippet demonstrates how to filter the array:

$new = array_filter($arr, function ($var) {
    return ($var['name'] == 'CarEnquiry');
});

In this case, the callback function ($var['name'] == 'CarEnquiry') checks if the 'name' value for each array element is equal to 'CarEnquiry'. If true, the element is included in the filtered array ($new).

Filtering by Interchangeable Values

If the filter value needs to be interchangeable, such as 'CarEnquiry' or 'Finance', a slight modification can be made to the callback function:

$filterBy = 'CarEnquiry'; // or Finance etc.

$new = array_filter($arr, function ($var) use ($filterBy) {
    return ($var['name'] == $filterBy);
});

By introducing the $filterBy variable, the filter criteria becomes dynamic, allowing for filtering by different values as needed.

The above is the detailed content of How Can I Filter a Two-Dimensional Array in PHP Based on a Specific Key\'s Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn