Converts single or multi root Nested Set database data into multidimensional array for using in the
jsTree widget

@param array $data
@param int $lft
@param null $rgt
@param int $root
@return array
196848
public function prepareNestedData($data, $lft = 0, $rgt = null, $root = 0)
    {
        $res = [];
        foreach ($data as $row) {
            $currentRoot = isset($row[$this->rootAttribute]) ? $row[$this->rootAttribute] : 0;
            if (is_null($rgt) || $row[$this->rightAttribute] < $rgt && $root == $currentRoot) {
                if ($lft + 1 == $row[$this->leftAttribute]) {
                    if ($row[$this->leftAttribute] + 1 !== $row[$this->rightAttribute]) {
                        $res[] = [
                            'id' => $row['id'],
                            'text' => $row[$this->modelLabelAttribute],
                            'a_attr' => [
                                'data-id' => $row['id'],
                            ],
                            'children' => self::prepareNestedData(
                                $data,
                                $row[$this->leftAttribute],
                                $row[$this->rightAttribute],
                                $currentRoot
                            ),
                            'state' => [
                                'selected' => in_array($row['id'], $this->selectedNodes),
                            ],
                        ];
                    } else {
                        $res[] = [
                            'id' => $row['id'],
                            'text' => $row[$this->modelLabelAttribute],
                            'a_attr' => [
                                'data-id' => $row['id'],
                            ],
                            'children' => [],
                            'state' => [
                                'selected' => in_array($row['id'], $this->selectedNodes),
                            ],
                        ];
                    }
                    $lft = $row[$this->rightAttribute];
                } else if ($row[$this->leftAttribute] == 1 && $root !== $currentRoot) {
                    $res[] = [
                        'id' => $row['id'],
                        'text' => $row[$this->modelLabelAttribute],
                        'a_attr' => [
                            'data-id' => $row['id'],
                        ],
                        'children' => self::prepareNestedData(
                            $data,
                            $row[$this->leftAttribute],
                            $row[$this->rightAttribute],
                            $currentRoot
                        ),
                        'state' => [
                            'selected' => in_array($row['id'], $this->selectedNodes),
                        ],
                    ];
                }
            }
        }
        return $res;
    }
496557
protected function _reformatData(Garp_Db_Table_Rowset $data) {
        $out = array();
        foreach ($data as $datum) {
            $out[$datum->identifier] = $datum->text;
        }
        return $out;
    }
458632
public function renderAsArray($data = false, $parent = 0)
    {
        $args = $this->setParameters(func_get_args());
        $tree = collect([]);

        $args['data']->each(function ($item) use (&$tree, $args) {

            $currentData = collect([]);

            if (intval($item[$this->parent]) == intval($args['parent'])) {
                // fill the array with the body fields
                foreach ($this->config['body'] as $field) {
                    $currentData->put($field, isset($item[$field]) ? $item[$field] : null);
                }

                // Get the child node name
                $child = $this->config['childNode'];

                $currentData->put($child, []);
                $currentData->put($this->parent, $item[$this->parent]);

                // Get the primary key name
                $item_id = $item[$this->config['primary_key']];
                // check the child element
                if ($this->hasChild($this->parent, $item_id, $args['data'])) {
                    // function call again for child elements
                    $currentData->put($child, $this->renderAsArray($args['data'], $item_id));
                }

                // current data push to global array
                $tree->push($currentData->toArray());
            }

        });

        return $tree->toArray();
    }
721118
private function buildTree(array $rows, $parent = null)
    {
        $tree = [];

        foreach ($rows as &$row) {
            if ($row['parent'] == $parent) {
                $hasChildren        = $this->propertyAccessor->getValue($row, "[{$this->options['children_column']}]");
                $row['hasChildren'] = (bool)($hasChildren > 0);
                $row['children']    = $this->buildTree($rows, $row['id']);
                $tree[]             = $row;
            }
        }

        return $tree;
    }
857027
private function _parseDataGroup($data, $item_callback)
    {   
        // 不要定义为 static, 否则最后多次调用会重复值
        $groups = array();
        if (is_array($data)) {              // 数组形式
            foreach ($data as $key => $value) {
                // 进行元素分析，元素的键为数字而值为数组，且其值的元素键为数字值为数组的进行递归
                if (is_numeric($key) && is_array($value)) {
                    // 方式一：分解数组为子项
                    //$temp = $this->_parseDataGroup($value, $item_callback); // 先临时存之
                    //$groups = array_merge($groups, $temp);
                    
                    // 方式二：不分解，在解析子项时处理数组格式
                    $groups[]   = call_user_func(array($this, $item_callback), $value);
                } elseif (!is_numeric($key) || !empty($value)) {    // 值不为空或键不是数字
                    $groups[]   = call_user_func(array($this, $item_callback), array($key => $value));
                }
            }
        } else {                            // 标量类型/null/其他，直接作为一个解析组
            $groups[]   = call_user_func(array($this, $item_callback), $data);
        }
        
        return $groups;
    }
488303
function ($currentRoot, data) {
      data.relationship = data.relationship || '001';
      var $table = $('<table>')
        .append($('<tr>').append($('<td colspan="2">').append(this.createNode(data))))
        .append('<tr class="lines"><td colspan="2"><div class="downLine"></div></td></tr>')
        .append('<tr class="lines"><td class="rightLine"></td><td class="leftLine"></td></tr>');
      this.$chart.prepend($table)
        .children('table:first').append('<tr class="nodes"><td colspan="2"></td></tr>')
        .children('tr:last').children().append(this.$chart.children('table').last());
    }
687890
public function setSchema(array $data)
    {
        foreach ($data as $tableData) {
            $this->tables[$tableData['name']] = (new Table($tableData['name']))
                        ->setPrimaryKey($tableData['pkey'])
                        ->setComment($tableData['comment'])
                        ->addColumns($tableData['columns']);
        }
        foreach ($data as $tableData) {
            $table = $this->definition($tableData['name']);
            foreach ($tableData['relations'] as $relationName => $relationData) {
                $relationData['table'] = $this->definition($relationData['table']);
                if ($relationData['pivot']) {
                    $relationData['pivot'] = $this->definition($relationData['pivot']);
                }
                $table->addRelation(new TableRelation(
                    $relationData['name'],
                    $relationData['table'],
                    $relationData['keymap'],
                    $relationData['many'],
                    $relationData['pivot'] ?? null,
                    $relationData['pivot_keymap'],
                    $relationData['sql'],
                    $relationData['par']
                ));
            }
        }
        return $this;
    }
321048
public function create(array $data = [])
    {
        $collection = parent::create($data);

        if ($this->getCurrentCategory() && $this->getCurrentCategory()->getLevel() >= 2) {
            $collection->addAttributeToFilter('entity_id', ['neq' => (int) $this->getCurrentCategory()->getId()]);

            $rootPath      = array_slice($this->getCurrentCategory()->getPathIds(), 0, 2);
            $pathCondition = implode('/', $rootPath) . '%';
            $collection->addFieldToFilter('path', ['like' => $pathCondition]);
        }

        return $collection;
    }
1324136
protected function setCustomFields($base, $data, array $model_registry = array())
    {
        if (count($this->customfieldgroups) > 0) {
        } else {
            return $base;
        }

        foreach ($this->customfieldgroups as $group) {
            $group_data   = $this->processQueryFields(json_decode($data->$group), $model_registry [$group]);
            $base->$group = $this->sortObject($group_data);
        }

        return $base;
    }
948135
public function buildTree($data, $row_level = 'parent')
    {
        $new = [];
        foreach ($data as $a) {
            if (null === $a->{$row_level}) {
                $a->{$row_level} = 0;
            }
            $new[$a->{$row_level}][] = $a;
        }

        return $this->createTree($new, Arr::get($new, 0, []));
    }
713901
public function getSet($root)
    {
        $child = ucfirst(AnInflector::pluralize($this->getChild()->name));
        $parent = $this->getJunctionAlias().'.'.$this->_child_key;
        $filters = $this->getQueryFilters();
        $filters['where'] = array($parent => $root);
        $options = array(
            'repository' => $this->getTargetRepository(),
            'query' => $filters,
            'root' => $root,
            'property' => $this->getChildKey(),
            'target_property' => $this->getTargetChildKey(),
            'child' => $this->getChildRepository(),
        );

        $set = AnService::get('anahita:domain.entityset.decorator.manytomany', $options);

        return $set;
    }
498295
private function internalDataListUpdateData($data, $actions): array
    {
        if (is_callable($data)) {
            $actionsList = [];
            foreach ($actions as $actionData) {
                if ($actionData[0] === 'filterBy') {
                    $class = $this->internalDataListClasses['IvoPetkov\DataListFilterByAction'];
                    $action = new $class();
                    $action->property = $actionData[1];
                    $action->value = $actionData[2];
                    $action->operator = $actionData[3];
                } elseif ($actionData[0] === 'sortBy') {
                    $class = $this->internalDataListClasses['IvoPetkov\DataListSortByAction'];
                    $action = new $class();
                    $action->property = $actionData[1];
                    $action->order = $actionData[2];
                } elseif ($actionData[0] === 'sliceProperties') {
                    $class = $this->internalDataListClasses['IvoPetkov\DataListSlicePropertiesAction'];
                    $action = new $class();
                    $action->properties = $actionData[1];
                } elseif ($actionData[0] === 'slice') {
                    $class = $this->internalDataListClasses['IvoPetkov\DataListSliceAction'];
                    $action = new $class();
                    $action->offset = $actionData[1];
                    $action->limit = $actionData[2];
                } else {
                    $class = $this->internalDataListClasses['IvoPetkov\DataListAction'];
                    $action = new $class();
                }
                $action->name = $actionData[0];
                $actionsList[] = $action;
            }
            $class = $this->internalDataListClasses['IvoPetkov\DataListContext'];
            $context = new $class();
            $context->actions = $actionsList;
            $dataSource = call_user_func($data, $context);
            if (is_array($dataSource) || $dataSource instanceof \Traversable) {
                $data = [];
                foreach ($dataSource as $value) {
                    $data[] = $value;
                }
            } else {
                throw new \InvalidArgumentException('The data source callback result is not iterable!');
            }
        }
        foreach ($actions as $action) {
            if ($action[0] === 'filter') {
                $this->internalDataListUpdateAllValuesIfNeeded($data);
                $temp = [];
                foreach ($data as $object) {
                    if (call_user_func($action[1], $object) === true) {
                        $temp[] = $object;
                    }
                }
                $data = $temp;
                unset($temp);
            } else if ($action[0] === 'filterBy') {
                $this->internalDataListUpdateAllValuesIfNeeded($data);
                $temp = [];
                foreach ($data as $object) {
                    $propertyName = $action[1];
                    $targetValue = $action[2];
                    $operator = $action[3];
                    $add = false;
                    if (!isset($object->$propertyName)) {
                        if ($operator === 'equal' && $targetValue === null) {
                            $add = true;
                        } elseif ($operator === 'notEqual' && $targetValue !== null) {
                            $add = true;
                        } elseif ($operator === 'inArray' && is_array($targetValue) && array_search(null, $targetValue) !== false) {
                            $add = true;
                        } elseif ($operator === 'notInArray' && !(is_array($targetValue) && array_search(null, $targetValue) !== false)) {
                            $add = true;
                        } else {
                            continue;
                        }
                    }
                    if (!$add) {
                        $value = $object->$propertyName;
                        if ($operator === 'equal') {
                            $add = $value === $targetValue;
                        } elseif ($operator === 'notEqual') {
                            $add = $value !== $targetValue;
                        } elseif ($operator === 'regExp') {
                            $add = preg_match('/' . $targetValue . '/', $value) === 1;
                        } elseif ($operator === 'notRegExp') {
                            $add = preg_match('/' . $targetValue . '/', $value) === 0;
                        } elseif ($operator === 'startWith') {
                            $add = substr($value, 0, strlen($targetValue)) === $targetValue;
                        } elseif ($operator === 'notStartWith') {
                            $add = substr($value, 0, strlen($targetValue)) !== $targetValue;
                        } elseif ($operator === 'endWith') {
                            $add = substr($value, -strlen($targetValue)) === $targetValue;
                        } elseif ($operator === 'notEndWith') {
                            $add = substr($value, -strlen($targetValue)) !== $targetValue;
                        } elseif ($operator === 'inArray') {
                            $add = is_array($targetValue) && array_search($value, $targetValue) !== false;
                        } elseif ($operator === 'notInArray') {
                            $add = !(is_array($targetValue) && array_search($value, $targetValue) !== false);
                        }
                    }
                    if ($add) {
                        $temp[] = $object;
                    }
                }
                $data = $temp;
                unset($temp);
            } elseif ($action[0] === 'sort') {
                $this->internalDataListUpdateAllValuesIfNeeded($data);
                usort($data, $action[1]);
            } elseif ($action[0] === 'sortBy') {
                $this->internalDataListUpdateAllValuesIfNeeded($data);
                $sortData = []; // save the index and the property needed for the sort in a temp array
                foreach ($data as $index => $object) {
                    $sortValue = isset($object->{$action[1]}) ? $object->{$action[1]} : null;
                    if (is_object($sortValue)) {
                        if ($sortValue instanceof \DateTime) {
                            $sortValue = $sortValue->getTimestamp();
                        } else {
                            $sortValue = null;
                        }
                    }
                    $sortData[] = [$index, $sortValue];
                }
                usort($sortData, function($value1SortData, $value2SortData) use ($action) {
                    if ($value1SortData[1] === null && $value2SortData[1] === null) {
                        $result = 0;
                    } else {
                        if ($value1SortData[1] === null) {
                            return $action[2] === 'asc' ? -1 : 1;
                        }
                        if ($value2SortData[1] === null) {
                            return $action[2] === 'asc' ? 1 : -1;
                        }
                        if ((is_int($value1SortData[1]) || is_float($value1SortData[1])) && (is_int($value2SortData[1]) || is_float($value2SortData[1]))) {
                            $result = $value1SortData[1] < $value2SortData[1] ? -1 : 1;
                        } else {
                            $result = strcmp($value1SortData[1], $value2SortData[1]);
                        }
                    }
                    if ($result === 0) { // if the sort property is the same, maintain the order by index
                        return $value1SortData[0] - $value2SortData[0];
                    }
                    return $result * ($action[2] === 'asc' ? 1 : -1);
                });
                $temp = [];
                foreach ($sortData as $sortedValueData) {
                    $temp[] = $data[$sortedValueData[0]];
                }
                unset($sortData);
                $data = $temp;
                unset($temp);
            } elseif ($action[0] === 'reverse') {
                $data = array_reverse($data);
            } elseif ($action[0] === 'shuffle') {
                shuffle($data);
            } elseif ($action[0] === 'map') {
                $this->internalDataListUpdateAllValuesIfNeeded($data);
                $data = array_map($action[1], $data);
            }
        }
        return $data;
    }
37701
public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
        if(is_array($attr)){
            $_attr = array();
            foreach ($attr as $key => $value) {
                $_attr[] = "{$key}=\"{$value}\"";
            }
            $attr = implode(' ', $_attr);
        }
        $attr   = trim($attr);
        $attr   = empty($attr) ? '' : " {$attr}";
        $xml   = "<{$root}{$attr}>";
        $xml   .= self::data_to_xml($data, $item, $id);
        $xml   .= "</{$root}>";
        return $xml;
    }
218252
protected function recursiveConvertArray($data)
    {
        $out = [];

        foreach ($data as $key => $value) {
            $nkey = $this->normalize($key);

            if (in_array($nkey, $this->ignoredAttributes)) {
                continue;
            }

            $out[$nkey] = is_scalar($value) ? $value : $this->convertValue($value);
        }

        return $out;
    }
46249
def next_root_lft
      last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first
      raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots?
      last_root.try(:right) || 0.to_r
    end
1105934
public static function toArray($data, bool $recursive = false)
    {
        $arr = [];

        // Ensure the input data is an array.
        if (\is_object($data)) {
            if ($data instanceof \Traversable) {
                $arr = \iterator_to_array($data);
            } elseif (\method_exists($data, 'toArray')) {
                $arr = $data->toArray();
            }
        } else {
            $arr = (array)$data;
        }

        if ($recursive) {
            foreach ($arr as $key => $value) {
                if (\is_array($value) || \is_object($value)) {
                    $arr[$key] = static::toArray($value, $recursive);
                }
            }
        }

        return $arr;
    }
1317178
public static function treeToList($tree, $child = '_child', $order = null, &$list = []): array
    {
        if (is_array($tree)) {
            foreach ($tree as $key => $value) {
                $refer = $value;
                if (isset($refer[$child])) {
                    unset($refer[$child]);
                    self::treeToList($value[$child], $child, $order, $list);
                }
                $list[] = $refer;
            }
            if ($order !== null) {
                $list = self::listSortBy($list, $order, 'asc');
            }
        }
        
        return $list;
    }