douyin4875 2017-01-18 23:08
浏览 42
已采纳

PHP:与关联数组数组中的特定键关联的返回值

In PHP 5.5+, how do I check if the given array of associative arrays contains specific key/value pairs. For example:

$some_array = array(
            array(
                "value"=> 1,
                "k1"=> "austin",
                "k2"=> "texas",
                "k3"=> "us"
            ),
            array(
                "value"=> 15,
                "k1"=> "bali",
                "k2"=> "ubud",
                "k3"=> "indonesia"
            ),
            array(
                "value"=> 26,
                "k1"=> "hyd",
                "k2"=> "telangana",
                "k3"=> "india"
            )
));

How do I return the value associated with k1='bali', k2='ubud' and k3='indonesia'? I can loop through each element to check if that combination exists in the array but is there a simpler way to handle this?

  • 写回答

1条回答 默认 最新

  • doukang8949 2017-01-18 23:18
    关注

    If you have an target array of keys and values, you can filter the main array to only include child arrays that match all the key/value combinations in your target array using array_diff_assoc.

    $target =array(
        "k1"=> "bali",
        "k2"=> "ubud",
        "k3"=> "indonesia"
    );
    
    $matches = array_filter($some_array, function($item) use ($target) {
        return !array_diff_assoc($target, $item);
    });
    

    Inside the array_filter callback, array_diff_assoc will return all the key/value pairs in $target that are not present in $item, so if they all match, you'll get an empty array. Negating that result with ! will return true for matching arrays and false for non-matching arrays.

    $matches will be an array of all the child arrays matching your set of key/value pairs, or an empty array if none match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容