Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a two dimensional array by value

Tags:

arrays

php

People also ask

How we can filter values evaluate values in NumPy array?

In NumPy, you filter an array using a boolean index list. A boolean index list is a list of booleans corresponding to indexes in the array. If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.

Can you pass two-dimensional array to function in C?

// The following program works only if your compiler is C99 compatible. If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array. In this method, we must typecast the 2D array when passing to function.

What is a 2x2 array?

The 2x2 Matrix is a decision support technique where the team plots options on a two-by-two matrix. Known also as a four blocker or magic quadrant, the matrix diagram is a simple square divided into four equal quadrants. Each axis represents a decision criterion, such as cost or effort.


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');

?>

If you want to make this a generic function use this:

function filterArrayByKeyValue($array, $key, $keyValue)
{
    return array_filter($array, function($value) use ($key, $keyValue) {
       return $value[$key] == $keyValue; 
    });
}

Above examples are using the exact word match, here is a simple example for filtering array to find imprecise "name" match.

  $options = array_filter($options, function ($option) use ($name) {
    return strpos(strtolower($option['text']), strtolower($name)) !== FALSE;
  });

array_filter is the function you need. http://php.net/manual/en/function.array-filter.php

Give it a filtering function like this:

function my_filter($elt) {
    return $elt['name'] == 'something';
}