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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里