PHP比较匹配键值对的两个数组

时间:2017-10-13 18:15:29

标签: php arrays

由于某种原因,已经醒了太多时间并且遇到了这个问题...

我正在尝试比较匹配的key =>值对的2个数组,并输出匹配的结果。

数组1: $from['modules']

Array( [8] => Array ( [object_module_id] => 8 [object_module_type] =>
CallLog [object_module_name] => Call Log ) [6] => Array (
[object_module_id] => 6 [object_module_type] => Files
[object_module_name] => Saved Files ) [7] => Array (
[object_module_id] => 7 [object_module_type] => Notes
[object_module_name] => Notes ))

数组2: $to[0]['modules']

Array( [4] => Array ( [object_module_id] => 4 [object_module_type] =>
CallLog [object_module_name] => Call Log ) [2] => Array (
[object_module_id] => 2 [object_module_type] => Files
[object_module_name] => ) [10] => Array ( [object_module_id] => 10
[object_module_type] => Images [object_module_name] => ) [3] => Array
( [object_module_id] => 3 [object_module_type] => Notes
[object_module_name] => Notes ) [1] => Array ( [object_module_id] => 1
[object_module_type] => Passengers [object_module_name] => Passengers
))

我想通过object_module_type&&amp ;;识别两个数组中找到的模块。 object_module_name并将匹配的结果作为数组转储到$module_matches[0]

鉴于以上数组,我知道应该有3个匹配(按类型和名称)

  1. Array1-> 8匹配Array2-> 4
  2. Array1-> 6匹配Array2-> 2
  3. Array1-> 7匹配Array2-> 3
  4. 我希望将每个匹配细节都放到一个类似上面列表的数组中。

    EX:

    Array( [1] = >Array( ['from'] => ([object_module_id] => 8
    [object_module_type] => CallLog [object_module_name] => Call
    Log) ['to'] => ([object_module_id] => 4 [object_module_type] => CallLog
    [object_module_name] => Call Log)) [2] => (...) [3] => (...))
    

    我当前的尝试:将结果转储到$module_matches[0]

    $module_matches[0] = array_intersect($to[0]['modules'], $from['modules']);
    

    但问题是$module_matches[0]最终只是首先输入array_intersect()的数组?在这种情况下,$module_matches[0]返回Array2。

1 个答案:

答案 0 :(得分:1)

尝试一下..

$matching_results = array();

foreach($from['modules'] as $from_id => $from_module){
    // Parse through each of the $from modules.
    $matches = 0;
    foreach($to[0]['modules'] as $to_id => $to_module){
        // Now we'll compare it to the $to modules...
        foreach($from_module as $from_key => $from_value){
            // So we'll break each $from module apart by key and val...
            if($to_module[$from_key] == $from_module[$from_key] && $from_key != 'object_module_id'){
                // If the array key isn't the ID, and if it matches
                // we'll increase our match counter by 1
                $matches++;
            }
        }
        if($matches == (count($from_module) - 1)){
            // the number of fields that need to match is
            // the total # of fields, minus the ID...
            $matching_results[$from_id] = $from_module;
        }
    }

}

var_dump($matching_results);