1515
1616class NestableCollection extends Collection
1717{
18- private $ total ;
19- private $ parentColumn ;
18+ private $ total = 0 ;
19+ private $ parentKey = null ;
2020
21- public function __construct ($ items = array ())
21+ public function __construct (array $ items = array (), $ parentKey = ' parent_id ' )
2222 {
2323 parent ::__construct ($ items );
24- $ this ->parentColumn = 'parent_id ' ;
2524 $ this ->total = count ($ items );
25+ $ this ->parentKey = $ parentKey ;
2626 }
2727
2828 /**
@@ -32,8 +32,8 @@ public function __construct($items = array())
3232 */
3333 public function nest ()
3434 {
35- $ parentColumn = $ this ->parentColumn ;
36- if (! $ parentColumn ) {
35+ $ parentKey = $ this ->parentKey ;
36+ if (! $ parentKey ) {
3737 return $ this ;
3838 }
3939
@@ -51,8 +51,8 @@ public function nest()
5151
5252 // add items to children collection
5353 foreach ($ this ->items as $ key => $ item ) {
54- if ($ item ->$ parentColumn && isset ($ this ->items [$ item ->$ parentColumn ])) {
55- $ this ->items [$ item ->$ parentColumn ]->items ->push ($ item );
54+ if ($ item ->$ parentKey && isset ($ this ->items [$ item ->$ parentKey ])) {
55+ $ this ->items [$ item ->$ parentKey ]->items ->push ($ item );
5656 $ keysToDelete [] = $ item ->id ;
5757 }
5858 }
@@ -70,15 +70,15 @@ public function nest()
7070 * @param BaseCollection|null $collection
7171 * @param integer $level
7272 * @param array &$flattened
73- * @param string $key
73+ * @param string $column
7474 * @param string $indentChars
7575 * @return array
7676 */
77- public function listsFlattened (BaseCollection $ collection = null , $ level = 0 , array &$ flattened = [], $ key = 'title ' , $ indentChars = ' ' )
77+ public function listsFlattened (BaseCollection $ collection = null , $ level = 0 , array &$ flattened = [], $ column = 'title ' , $ indentChars = ' ' )
7878 {
7979 $ collection = $ collection ? : $ this ;
8080 foreach ($ collection as $ item ) {
81- $ flattened [str_repeat ($ indentChars , $ level ) . $ item ->$ key ] = $ item -> id ;
81+ $ flattened [$ item -> id ] = str_repeat ($ indentChars , $ level ) . $ item ->$ column ;
8282 if ($ item ->items ) {
8383 $ this ->listsFlattened ($ item ->items , $ level + 1 , $ flattened );
8484 }
0 commit comments