简体   繁体   中英

PHP - Loop through nested array and increase foreach

I have a huge JSON array which has categories, sub categories, sub-sub categories etc.

It could continue to grow in future without my control so wondering how best to continue to go through each category and their ['children'] elements until no results found.

My approach so far is surely too basic? Wondering what would be a better approach ideally.

foreach( $json['results'] as $parent_cat ) {
// var_dump($parent_cat['path']);

foreach( $parent_cat['children'] as $sub_cat ) {
  // var_dump($sub_cat['path']);

  foreach( $sub_cat['children'] as $sub_sub_cat ) {
    // var_dump($sub_sub_cat['path']);

    foreach( $sub_sub_cat['children'] as $sub_sub_sub_cat) {
      // var_dump($sub_sub_sub_cat['path']);

      foreach( $sub_sub_sub_cat['children'] as $sub_sub_sub_sub_cat) {
        // var_dump($sub_sub_sub_sub_cat['path']);

        foreach( $sub_sub_sub_sub_cat['children'] as $sub_sub_sub_sub_sub_cat) {
          // var_dump($sub_sub_sub_sub_sub_cat['path']);

          foreach( $sub_sub_sub_sub_sub_cat['children'] as $sub_sub_sub_sub_sub_sub_cat) {
            // var_dump($sub_sub_sub_sub_sub_sub_cat['path']);

            foreach( $sub_sub_sub_sub_sub_cat['children'] as $sub_sub_sub_sub_sub_sub_cat) {
              var_dump($sub_sub_sub_sub_sub_sub_cat['path']);
            }
          }
        }
      }
    }
  }
}

}

instead of all this hassle just usearray_walk_recursive if you want to fetch path,

array_walk_recursive($arr, function($v,$k) use(&$r){
    if($k == 'path'){
        $r[] = $v;
    }
});
print_r($r);

Recursion is a typical approach to work with nested data.

<?php

class ResultsDumper {
    public function dumpRecursive( array $parent_cat ) {
        var_dump( $parent_cat['path'] );

        if ( isset( $parent_cat['children'] ) ) {
            foreach ( $parent_cat['children'] as $sub_cat ) {
                // Notice how this function is calling itself
                $this->dumpRecursive( $sub_cat );
            }
        }
    }
}

$resultsDumper = new ResultsDumper();
$resultsDumper->dumpRecursive( $json['results'] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM