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.

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100