douliangpo0128 2018-02-09 22:53
浏览 49
已采纳

php在assoc数组中找到公共密钥

I have an array

  "a" => array:99 [▶]
  "b" => array:98 [▶]
  "c" => array:98 [▶]
  "d" => array:98 [▶]
  "e" => array:98 [▶]
  "f" => array:98 [▶]
  "g" => array:97 [▶]
  "h" => array:72 [▶]

.....

I need to filter the arrays by common keys. array a has 99 items and h has 72 items so I need to make all the arrays in this array the same 72 items based on the key.

array a:

"Johnson" => "2.94"
"Jordan" => "1.99"
"Bob" => "3.29"
"Bill" => "2.60"
"Jon" => "3.82"

......

array b:

"Johnson" => "2.94"
"Jordan" => "1.99"
"Bob" => "3.29"
"Bill" => "2.60"
"Steve" => "3.82"

......

so I essentially want the arrays a and b to be:

"Johnson" => "2.94"
"Jordan" => "1.99"
"Bob" => "3.29"
"Bill" => "2.60"

because these are the keys that are consistent across those 2 arrays.

I would need each of the arrays to have the same items based on the key that exists in all of the arrays.

Is there a way to do this if the arrays are part of the same array?

  • 写回答

2条回答 默认 最新

  • donglanzhan7151 2018-02-10 00:17
    关注

    First apply array_intersect_key once with all the subarrays passed to it. This you can do with call_user_func_array: this will give you the result for the first item in your data. It will only have the keys remaining that also occur in all other items.

    Then map the data with array_map by applying again array_intersect_key to intersect each item with that first item's result.

    Assuming your input is stored in a variable named $data:

    $first = call_user_func_array('array_intersect_key', $data);
    $result = array_map(function ($item) use ($first) {
        return array_intersect_key($item, $first);
    }, $data);
    

    $result will have a copy of the data where each item will have the same keys (but still with their proper values of course).

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c