Filter a 2D array by the value of a specific key

How can I filter this array to only store items with [category] => 1?

[0] => Array
    (
        [link] => index
        [image] => spot
        [category] => 0
    )

[1] => Array
    (
        [link] => test
        [image] => spotless
        [category] => 0
    )

[2] => Array
    (
        [link] => differentcat
        [image] => spotly
        [category] => 1
    )
+1
source share
4 answers

Use array_filter.

You need something like this (assuming you want to save entries with category1):

function categoryone($var)
{
    return (is_array($var) && $var['category'] == 1);
}

print_r(array_filter($your_array, "categoryone"));
+6
source

You can use array_filterthat checks the value of a category in a callback. http://php.net/manual/en/function.array-filter.php

+2
source

:

function filter_function($var) {
    return is_array($var) && $var['category'] == 1;
}

... array_filter(), :

$filtered_array = array_filter($my_array, 'filter_function');

: , , .

+2

@pathros:

To use a different value for filtering, the solution is as follows: (TESTED :-))

//Define your array
$my_array = array(
  0 =>   array(
    'cat' =>         '1',
    'value' =>         'Value A'
    )
  ,
  1 =>   array(
    'cat' =>         '2',
    'value' =>         'Value B'
    )
  ,
  2 =>   array(
    'cat' =>         '0',
    'value' =>         'Value C'
    )
  ,
  3 =>   array(
    'cat' =>         '1',
    'value' =>         'Value D'
    )
  );

//Define your filtering function
function my_filtering_function($in_array) {
    return is_array($in_array) && $in_array['cat'] == $GLOBALS['filter_param_1'];
}

//TEST #1 : Set the desired value to 2
$GLOBALS['filter_param_1'] = 2;
//Filter your array to only return items that match "cat=2"
$filtered_array = array_filter($my_array, 'my_filtering_function');
e('Number of matching records : '.count($filtered_array)).'record(s)<br>'; //Will return "1 record(s)" (the second record of your array)

//TEST #2 : Set the desired value to 1
$GLOBALS['filter_param_1'] = 1;
//Filter your array to only return items that match "cat=1"
$filtered_array = array_filter($my_array, 'my_filtering_function');
e('Number of matching records : '.count($filtered_array)).'record(s)<br>'; //Will return "2 record(s)" (the first and the last of your array)
0
source

Source: https://habr.com/ru/post/1721453/


All Articles