douyan8772 2018-12-04 17:13
浏览 80
已采纳

Php过滤键和值的多维关联数组

I am trying to write a function to filter a multidimensional associative array where the query array must match both with all keys and all values.

For example I need to filter this:

$data = array(
       array("id"=>"1","color"=>"Red","size" => "L"),
       array("id"=>"2","color"=>"Blue","size"  => "L"),
       array("id"=>"3","color"=>"Blue","size"  => "L")
    );

and the parameter I need to match are provided in an array like:

array("color"=>"Red","size" => "L")

So the I should get from the first array:

array("id"=>"1","color"=>"Red","size" => "L")

that is the only one that matches exactly all key names and values.

I have idea to iterate the array and to compare each value like:

$value['color'] == $query['color'] && $value['size'] == $query['size'] . . .

but I do not think is the best and i would like to write a more general function not with hardcoded array keys. How can I do?

  • 写回答

3条回答 默认 最新

  • douyigua5381 2018-12-04 17:32
    关注

    Why not to use the mathematician set theory and intersection? In Php array terms, it means you can use array_intersect to get the equal values from two arrays.

    public function filter(array $query, array $data) : array
    {
        $result = array_filter($data, function ($item) use ($query) 
        {
            $valueInters = array_intersect($item,$query);
            $keyIntersec = array_intersect(array_flip($valueInters),array_flip($query));
            return ( count($valueInters) == count($query) && (count($keyIntersec)) == count($query));        
        });
        return $result;
    }
    

    Brief explanation: the function iterates the array of array you need to filter. Each sub array is intersected with the query array, and the result is an array only with the similar value from both. Then if the length of this last one is the same as the query, that means you matched exactly all the value in the query param.

    Since you want to be sure the value matched correspond to the same key, you flip both query array and the array to be filtered then you do the same as previously done.

    Nothing is hardcoded and is a general code you can use just passying data to be filtered and query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?