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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条