1

次の多次元配列があるとします。

$family = array(
    "grandfather",
    "grandmother",    
    "father" => array(
        "parents" => array(
            "grandfather",
            "grandmother"
         )
    ),
    "mother" => array(
        "parents" => array(
            "grandfather",
            "grandmother"
         )
    ),
    "son" => array(
        "parents" => array(
            "father",
            "mother"
         )
    ),
    "daughter" => array(
        "parents" => array(
            "father",
            "mother"
         )
    ),
);

この配列を拡張して、曾祖父母、曾孫などを含めることを想像できます。

これは一般的で十分に文書化されたデータ構造であると確信していますが、私はコンピューター サイエンスを専攻していないため、この特定の種類の辞書を説明または命名する方法がわかりません。

私たちが探している「子」ノードと「先祖」ノードの名前が与えられた場合、このツリーを確実にナビゲートする PHP に組み込まれた関数はありますか?

例えば:

getAncestor($array, $child, $ancestor);

私はこれを試しましたが、通常は getAncestor() 関数がネストされた再帰が含まれますが、「行き止まり」に陥ることがあり、1 つのブランチの最後までナビゲートします。

4

2 に答える 2

0

より直線的なアプローチを試すことができます。すべてを互いに入れ子にする代わりに、各オブジェクトのすべての先祖へのポインターをたくさん持つだけです。そうでなければ、これは再帰問題のように思えます。

ポインターアプローチ:

<?php

$person1 = new PersonObject( 'details' );
$person2 = new PersonObject( 'details' );

$person1->father =& $person2;

?>

あなたのデータセットがあなたの例のように与えられている場合、検索する必要がある祖先の数に応じて、この種のシステムに変換することでメリットがある場合とない場合があります。また、私の意見では、この構造の方がずっときれいです =)。

于 2013-02-01T02:07:37.230 に答える
0

申し訳ありませんが、それを見ずに曽祖父母を追加する方法を想像できません. あなたは再帰が必要だと言いますが、$family2 レベルのネストしかない 3 世代のメンバーがあります。そのように曽祖父母を追加した場合(サンプル配列に基づく私の最善の推測$family)、ネストは 2 レベルしかありません。

$family = array(
    "great-grandfather",
    "great-grandmother",    
    "grandmother" => array(
        "parents" => array(
            "great-grandmother",
            "great-grandfather"
         )
    ),
    // ...
);

その場合、再帰は必要ありません。

あなたの説明に基づいて正確に何をすべきかは不明ですが。一致が見つかった場合、子と先祖をエコーアウトし、ブール値の結果を返します。

function getAncestor($array, $child, $ancestor)
{
    foreach($array as $_child => $_ancestor) {
        // Bail if child is not a match or ancestor is not array
        if($child != $_child ||
           !is_array($_ancestor) || !count($_ancestor))
            continue;

        // see if cur ancestor is a match for searched ancestor
        if(in_array($ancestor, $_ancestor['parents'])) {
            echo 'Child: ' . $child . PHP_EOL;
            echo 'Ancestors: ' . implode(', ', $_ancestor['parents']) . PHP_EOL;
            return true;
        }
    }

    return false;
}

getAncestor($family, 'son', 'father');
getAncestor($family, 'father', 'grandmother');
getAncestor($family, 'father', 'mother');

出力

子供:息子

先祖:父、母

子供:父

先祖:祖父、祖母

この例のもう 1 つの注意点は、が同じ親を持っている$familyように見えることです。

于 2013-02-03T05:01:10.060 に答える