[Solved] Searching for an array key branch inside a larger array tree – PHP


I think (and you have confirmed) that you can represent your data as an XML structure. I this case, you can use XPath to find any branch in your data. Here is sample XML data inferred from your question:

<?xml version="1.0" encoding="utf-8" ?>
<stmt_echo>
    <subnodes>
        <exprs>
            <expr_constfetch>
                <subnodes>
                    <name>
                        <name>
                            <subnodes>
                                <parts>
                                    <part>true</part>
                                    <!-- more items -->
                                </parts>
                            </subnodes>
                        </name>
                    </name>
                </subnodes>
            </expr_constfetch>
            <!-- more items -->
        </exprs>
    </subnodes>
</stmt_echo>

And here is the PHP code to locate the node you mentioned:

$doc = new DOMDocument;
$doc->Load("test.xml");

$xpath = new DOMXPath($doc);
$nodes = $xpath->query("//subnodes/parts[part="true"]");

foreach($nodes as $node) {
    dumpNodePath($node);
}

# Output
# /stmt_echo/subnodes/exprs/expr_constfetch/subnodes/name/name/subnodes/parts

function dumpNodePath($node) {
    $path = array($node->tagName);
    while ($node = $node->parentNode) {
        if ($node->nodeType != XML_DOCUMENT_NODE) {
            $path[] = $node->tagName;
        }
    }
    echo "https://stackoverflow.com/" . implode("https://stackoverflow.com/", array_reverse($path)) . "\n";
}

6

solved Searching for an array key branch inside a larger array tree – PHP