Skip to content

Commit

Permalink
Add nestedToArray to treecollection (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
damsfx authored Nov 22, 2024
1 parent 626409c commit 7ed916a
Show file tree
Hide file tree
Showing 3 changed files with 414 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Database/Traits/NestedTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
* $query->leaves(); // Filters as all final nodes without children.
* $query->getNested(); // Returns an eager loaded collection of results.
* $query->listsNested(); // Returns an indented array of key and value columns.
* $query->nestedArray(); // Returns an nested array of key and values columns.
*
* Flat result access methods:
*
Expand Down Expand Up @@ -518,6 +519,19 @@ public function scopeGetNested($query)
return $query->get()->toNested();
}

/**
* Gets an nested array with values of a given columns.
*
* @param \Illuminate\Database\Query\Builder $query
* @param mixed $columns Model columns to return, either a string name of the role or an array of names.
* @param string $key Model column to use as key
* @return array
*/
public function scopeNestedArray($query, $columns, $key = null)
{
return $query->get()->toNestedArray($columns, $key);
}

/**
* Gets an array with values of a given column. Values are indented according to their depth.
*
Expand Down
57 changes: 57 additions & 0 deletions src/Database/TreeCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,61 @@ public function listsNested($value, $key = null, $indent = '   ')
$rootItems = $this->toNested();
return $buildCollection($rootItems);
}

/**
* Gets an nested array with values of a given columns.
* @param mixed $values Model columns to return, either a string name of the role or an array of names.
* @param string $key Model column to use as key
* @return array
*/
public function toNestedArray($values, $key = null)
{
if (!is_array($values)) {
$values = [$values];
}

/*
* Recursive helper function
*/
$buildCollection = function ($items) use (&$buildCollection, $values, $key) {
$result = [];

foreach ($items as $item) {
$itemArray = [];

if ($key !== null) {
$itemArray[$item->{$key}] = $item->only($values);
}
else {
$itemArray = array_merge($itemArray, $item->only($values));
}

/*
* Add the children
*/
$childItems = $item->getChildren();
if ($childItems->count() > 0) {
if ($key !== null) {
$itemArray[$item->{$key}]['children'] = $buildCollection($childItems);
} else {
$itemArray = array_merge($itemArray, ['children' => $buildCollection($childItems)]);
}
}

if ($key !== null) {
$result = $result + $itemArray;
} else {
$result[] = $itemArray;
}
}

return $result;
};

/*
* Build a nested collection
*/
$rootItems = $this->toNested();
return $buildCollection($rootItems);
}
}
Loading

0 comments on commit 7ed916a

Please sign in to comment.