2015-07-10 122 views
2

首先解释我想要做的事情:我将数组作为某人的家族树。我带两个人,在我的mysql数据库中根据信息创建他们的家族树,然后我想检查他们是否有任何家庭连接。像可以说personA的祖父可能是personB的曾祖父。了解家庭联系是否存在于其中,是非常重要的。我的意思是我必须知道,例如personA爷爷personB曾祖父。这将意味着连接位于阵列a 2级阵列和阵列b 3级阵列之间。在这种情况下,我必须知道这些数字和。在两个多维数组中查找和定位多个值

所以我有两个多维数组,名称为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"]=> "" 
            } 
       } 
} 

所以,如果我有2个阵列像我向您展示了上面,我怎么能检查是否有在数组“A”的任何相同的价值观和'b'?

+0

我认为你在寻找这个:http://stackoverflow.com/questions/5653241/using-array-intersect-on-a-multi-dimensional-array –

+0

据我可以告诉'array_intersect'只会删除一切,除非被检查的人是兄弟姐妹和他们的树是相同的。 –

回答

2

这里的算法应该是:

  1. 计算使用array_intersect
  2. 树木之间共享的每个ID每棵树
  3. 相交的ID的集合中的所有的人的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); 
} 

请注意,此代码是未经测试,但你应该得到的总体思路 - 这是很自然的递归处理您的阵列。