21282

Flatten a multdimensional Tree array in PHP

Question:

I have a Tree structured array with parent child relations. I want the array to be flattened for easy parsing.

Array ( [0] => Array ( [ParentID] => 11653 [FolderID] => 11823 [Items] => Array ( [0] => Array ( [ParentID] => 11823 [FolderID] => 11824 [Items] => Array ( [0] => Array ( [ParentID] => 11824 [FolderID] => 11827 [Items] => Array ( [0] => Array ( [ParentID] => 11827 [FolderID] => 11828 ) ) ) ) ) [1] => Array ( [ParentID] => 11823 [FolderID] => 11825 [Items] => Array ( [0] => Array ( [ParentID] => 11825 [FolderID] => 11826 ) ) ) ) ) )

Desired output :

Array ( [0] => Array ( [ParentID] => 11653 [FolderID] => 11823 ) [1] => Array ( [ParentID] => 11823 [FolderID] => 11824 ) [2] => Array ( [ParentID] => 11824 [FolderID] => 11827 ) [3] => Array ( [ParentID] => 11827 [FolderID] => 11828 ) [4] => Array ( [ParentID] => 11823 [FolderID] => 11825 ) [5] => Array ( [ParentID] => 11825 [FolderID] => 11826 ) )

I Have tried many flattening logic found in here, but i couldn't get the desired output.

Answer1:

Using <a href="http://www.php.net/manual/en/function.array-walk-recursive.php" rel="nofollow">array_walk_recursive</a> where $array is your array and $new_array is the flattened array.

array_walk_recursive($array, function($item, $key) use (&$new_array, &$i) { $new_array[(int) $i][$key] = $item; ($key == 'ParentID') ?: $i++; }); var_dump($new_array);

If you want it for parsing you could also just do:

array_walk_recursive($array, function($item, $key) { *Your parsing for each array* });

Answer2:

This function works well for flattening multi-dimensional arrays:

function array_flatten($array) { if(!is_array($array)) { return FALSE; } $result = array(); foreach($array as $key => $value) { if(is_array($value)) { $result = array_merge($result, array_flatten($value)); } else { $result[$key] = $value; } } return $result; }

Answer3:

Start with a static variable.

Then create a function which accepts an array, iterates over it, and adds an element to your static variable with the ParentID and FolderID. If the array also contains an element with name "Items" and is an array, then apply it recursively to this function.

Recommend

  • How to get the item count for sub-categories on each parent?
  • TypeError: Cannot find function hasNext in object (Folder with date ID)
  • How to model hierarchical data types in Haskell?
  • Create folders from folder id and parent id in java
  • Trying to flatten PDF using flattenPages() but nothing happens
  • How to get the array of sheet ids in a folder with python
  • Flattening a list of tuples [duplicate]
  • Multiply 2D NumPy arrays element-wise and sum
  • Regex with Non-capturing Group
  • Avoid Inheriting Super Class Tests in ScalaTest
  • Selecting a subset of data in ServiceStack.OrmLite
  • Real Time CountDown Timer In Python
  • NUnit 3.0 TestCase const custom object arguments
  • ASP.NET MVC 2 Preview 2 - display directory list rather than home/index
  • RxJava debounce by arbitrary value
  • ListItem.Attributes.Add not working
  • onBackPressed() not being executed
  • ilmerge with a PFX file
  • Why value captured by reference in lambda is broken? [duplicate]
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Can Jackson SerializationFeature be overridden per field or class?
  • Join two tables and save into third-sql
  • Deserializing XML into class C#
  • ActionScript 2 vs ActionScript 3 performance
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • php design question - will a Helper help here?
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Why joiner is not used after Sequence generator or Update statergy
  • python draw pie shapes with colour filled
  • Recursive/Hierarchical Query Using Postgres
  • Reading document lines to the user (python)
  • Binding checkboxes to object values in AngularJs
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Net Present Value in Excel for Grouped Recurring CF
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?
  • How do I use LINQ to get all the Items that have a particular SubItem?