Home > other >  filter of associative array with dynamic filter
filter of associative array with dynamic filter

Time:05-08

I am beginner with php.

I have two Assosiative Arrays , first is users

I have users associative Array like this

$users = array(
  0 => array(
    "name" => "ali",
    "age" => 22,
    "score" => 12
  ),
  1 => array(
    "name" => "hasan",
    "age" => 32,
    "score" => 52
  ),
);

Also , I have a Filter Array like this , that elements count is not fixed , for example "age" can exist or not ! and also others

$filters = array(
  "name" => "ali",
  "age" => 22
);

I need to filter this array dynamically depending on this $filters

function filterFunc($item)
{

  // i dont how what should write here
}
$filtered_users = array_filter($users, 'filter');

But , I don't know how to do it ?

CodePudding user response:

To filter, you need to iterate over all the filters in the filterFunc callback function and check if the filter applies. If one does not apply return false immediatly, else return true:

<?php

$users = array(
    0 => array(
    "name" => "ali",
    "age" => 22,
    "score" => 12
    ),
    1 => array(
    "name" => "hasan",
    "age" => 32,
    "score" => 52
    ),
);

$filters = array(
    "name" => "ali",
    "age" => 22
);

function filterFunc($item) {
    global $filters;
    foreach ($filters as $key => $value) {
        if ($item[$key] != $value) {
            return false;
        }
    }
    return true;
}
$filtered_users = array_filter($users, "filterFunc");   
print_r($filtered_users);

?>
  •  Tags:  
  • php
  • Related