Recursively loop each array path

I have the following (json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I am trying to figure out how to recursively navigate it so that I can see all the different paths that are in the array.

It can be 4 separate echoes or 4 lines of a line. >can be replaced by anything or nothing at all. If each line was echoed separately or placed in an array, which is likely to give maximum flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can’t circle my head around, so any help would be appreciated.

I think that I can somehow cycle through all:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
+6
source share
6 answers

. , . RecursiveIteratorIterator

// 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.'<br>';
}

: - https://eval.in/915070

+6

, .

while(count($array) != count($array, 1))    // stop when $array is one dimension
{
    $temp = [];
    foreach($array as $k => $v)
    {
        if(is_array($v))
        {
            if(count($v) != count($v, 1))  // check if reached the inner most array
            {
                foreach($v as $kk => $vv)
                {
                    $temp[$k . ' - ' . $kk] = $vv;
                }
            }
            else
                $temp[$k] = '(' . implode($v, ', ') . ')';
        }else
            $temp[$k] = $v;
    }
    $array = $temp;
}

foreach($array as $k => $v)
    echo $k . ' - ' . $v . "\n";

:


+2

. . ( ). :

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

function traverse_array($array,$key="",$prev="",&$final_op=array())
{
  if(is_array($array))
  {
    $prev .= $key." - ";
    foreach ($array as $key => $value) {
      traverse_array($value,$key,$prev,$final_op);
    }
  }
  else
  {

    $prev =trim($prev," - ");            
    $final_op[$prev][]=$array;
  }
  return $final_op;
}
$data = traverse_array($obj);
foreach ($data as $key => $value) {
  echo $key." (".implode(",", $value).")";
  echo PHP_EOL;
}

DEMO

+2

,

$obj = json_decode('{"Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}');


recursive($obj);

function recursive($obj){

    if(is_array($obj)){

        foreach ($obj as $k => $v) {
            echo $v." ";
        }

        return;
    }

    foreach ($obj as $key => $value) {
        echo $key. " =>";
        recursive($value);
    }

    echo "\n";

}

Group1 =>Blue =>Round =>Harold Arthur Tom 
Green =>Round =>Harold Circle =>Todd Mike 
Group2 =>Blue =>Round =>Peter 
0

- . . . : 4- .

* , , :

# 1 - - : ()

$array=json_decode('{
    "Group1": {
        "Blue": {
            "Round": {
                "One": [
                    "Lawrence",
                    "Anant",
                    "B."
                ],
                "Two": [
                    "Erwin"
                ]
            }
        },
        "Green": [
           "Bryan",
           "Mick"
        ]
    },
    "Group2": [
        "Peter",
        "Kris"
    ]
}', true);

function recurse($array,$path=''){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element value
            echo ($path?"$path > ":''),"$k > (".implode(', ',$v).")\n";  // don't recurse, just implode the indexed elements
        }else{                                                           // recurse because at least 2 levels below
            recurse($v,($path?"$path > $k":$k));                         // build path appropriately
        }
    }
}
recurse($array);

:

Group1 > Blue > Round > One > (Lawrence, Anant, B.)
Group1 > Blue > Round > Two > (Erwin)
Group1 > Green > (Bryan, Mick)
Group2 > (Peter, Kris)

# 2 - 4- : ()

function recurse($array,$path='',&$result=[]){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element value
            $result[]=($path?"$path > ":'')."$k > (".implode(', ',$v).')';  // don't recurse, just implode the indexed elements
        }else{  // recurse because at least 2 levels below
            recurse($v,($path?"$path > ":'').$k,$result);  // build path appropriately
        }
    }
    return $result;
}
var_export(recurse($array));

:

array (
  0 => 'Group1 > Blue > Round > One > (Lawrence, Anant, B.)',
  1 => 'Group1 > Blue > Round > Two > (Erwin)',
  2 => 'Group1 > Green > (Bryan, Mick)',
  3 => 'Group2 > (Peter, Kris)',
)

:

, , - json ( / ):

: ()

$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Lawrence" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Anant" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "B." },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Two", "tier5": "Erwin" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Bryan" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Mick" },
{ "tier1": "Group2", "tier2": "Peter" },
{ "tier1": "Group2", "tier2": "Kris" }]',true);

foreach($seperateArray as $row){
    $last_val=current(array_splice($row,-1));  // extract last element, store as string
    $results[implode(' > ',$row)][]=$last_val;
}
foreach($results as $k=>$v){
    echo "$k > (",implode(', ',$v),")\n";
}
// same output as earlier methods
0
source

Here is my trick with the generator function:

function paths(array $a)
{
    // if first item is an array, recurse
    if (is_array(reset($a))) {
        foreach ($a as $k => $v) {
            foreach (paths($v) as $path) {
                // yield "key - subpath"
                yield sprintf('%s - %s', $k, $path);
            }
        }
    } else {
        // yield leaf
        yield sprintf('(%s)', implode(', ', $a));
    }
}

foreach (paths($obj) as $path) {
    printf("%s\n", $path);
}

Try it online .

0
source

All Articles