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 关于github的项目怎么在pycharm上面运行
  • ¥15 内存地址视频流转RTMP
  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 找一个QT页面+目标识别(行人检测)的开源项目
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码