Recursively cycle every path of an array

后端 未结 6 1760
[愿得一人]
[愿得一人] 2021-01-01 01:02

I have the following(json) object:

$obj = json_decode(\'{
    \"Group1\": {
        \"Blue\": {
            \"Round\": [
                \"Harold\",
                 


        
6条回答
  •  有刺的猬
    2021-01-01 01:11

    Tested only on the given sample. But this should work if array levels are increased. I mainly use RecursiveIteratorIterator class functions

    // Initialize RecursiveIteratorIterator
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($obj), RecursiveIteratorIterator::SELF_FIRST);
    $paths = array(); // Paths storage
    foreach ($iterator as $k => $v) { // Loop thru each iterator
    
        if (!$iterator->hasChildren()) { // Check if iterator hasChildren is false
            $innermost = $iterator->getSubIterator($iterator->getDepth()); // Get innermost child which is the array
            for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { // Loop and push each path to the innermost array
                $p[] = $iterator->getSubIterator($i)->key();
            }
            array_pop($p); // Remove key
            $innermost = (array)$innermost; // Cast innermost to array
            $p[] = '(' . implode(', ', $innermost) . ')'; // push formatted innermost array to path
            $path = implode(' - ', $p); // implode the path
            $paths[] = $path; // store to list of paths array
        }
    
    }
    
    $paths = array_unique($paths); // remove exactly same paths
    
    foreach ($paths as $value) {  // Loop and echo each path
        echo $value.'
    '; }

    Output:- https://eval.in/915070

提交回复
热议问题