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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探