查找和定位两个多维数组中的多个值


Finding and locating multiple values in two multidimensional arrays

首先解释一下我要做的事情:我将数组作为某人的家谱。我取两个人,从我的mysql数据库中的信息做出他们的家谱,然后我想检查他们是否有任何家庭联系。比如personA的祖父可能是personB的曾祖父。了解家庭联系是否存在于哪个层次是非常重要的。我的意思是我必须知道例如personA祖父是否是personB曾祖父。表示连接在阵列a二级阵列和阵列b三级阵列之间。在这种情况下,我必须知道这些数字23

所以我有两个多维数组名称ab。我需要找出数组ab之间是否有任何多个值,如果有一些多个值,我必须找出它们在数组a和数组b中的位置。


我的数组是这样的:

[0]=> array(4) { 
    ["id"]=> "1" 
    ["father"]=> [0]=> array(4) { 
                     ["id"]=> "11" 
                     ["father"]=> [0]=> array(4) { 
                                      ["id"]=> "111" 
                                      ["father"]=> "" 
                                      ["mother"]=> ""
                                  }  
                     ["mother"]=> [0]=> array(4) { 
                                      ["id"]=> "112" 
                                      ["father"]=> "" 
                                      ["mother"]=> ""
                                  }  
                 } 
    ["mother"]=> [0]=> array(4) { 
                     ["id"]=> "12" 
                     ["father"]=> [0]=> array(4) { 
                                      ["id"]=> "121" 
                                      ["father"]=> "" 
                                      ["mother"]=> ""
                                  }  
                     ["mother"]=> [0]=> array(4) { 
                                      ["id"]=> "122" 
                                      ["father"]=> "" 
                                      ["mother"]=> ""
                                  }  
                 } 
}

如果我有两个数组,就像我上面展示的那样,我如何检查数组'a'和'b'中是否有相同的值?

这里的算法应该是:

  1. 计算每棵树中所有人id的集合
  2. 使用array_intersect使id相交
  3. 对于树之间共享的每个ID,在每个图中找到它并以某种方式报告。

我不知道您想如何报告共同祖先,所以这里是步骤1和2的实现。此外,我还提供了一个函数,用于计算到特定ID的"路径";路径是由字母M或F组成的字符串,指定给定ID在祖先树中的位置。例如,MF表示外祖父(母亲的父亲)。

function gather_ids($tree) {
    if (!is_array($tree)) return array();
    return array_merge(array($tree["id"]),
                       gather_ids($tree["mother"]),
                       gather_ids($tree["father"]));
}
function common_ancestors($tree_a, $tree_b) {
    return array_intersect(gather_ids($tree_a), gather_ids($tree_b));
}
function ancestor_path_recursive($path, $tree, $id) {
    if (!is_array($tree)) return NULL;
    if ($tree["id"] == $id) return $path;
    $p = path_to_id_recursive($path .. "M", $tree["mother"], $id);
    if (!is_null($p)) return $p;
    return path_to_id_recursive($path .. "F", $tree["father"], $id);
}
function ancestor_path($tree, $id) {
    return ancestor_path_recursive("", $tree, $id);
}

请注意,这段代码是未经测试的,但您应该了解总体思路—递归地处理数组是非常自然的。