Laravel etrepat/baum How to show whole tree - php

how can I show the whole tree. I have a 3 Level Navigation (First is root). With that code, I will only see the 2nd Level.
$tree = \App\Category::where('identifier', 'soccer')->first();
foreach($tree->getDescendants()->toHierarchy() as $descendant) {
echo "{$descendant->name} <br>";
}

You can get the whole tree including root by doing:
$root = Table::where('id', '=', $id)->first();
$tree = $root->getDescendantsAndSelf()->toHierarchy();
Now as $tree is Tree structure you need to traverse it recursively or with a queue data structure (DFS or BFS). Each item on the tree will have a children property with its children
Some pseudo for traversing would be:
function traverseBFS(tree) {
q = Queue()
q.push(tree[0]);
while (!q.empty()) {
item = q.top(); q.pop();
// do what you need with item
foreach (item->children as child) {
q.push(child);
}
}
}

Related

Assigning PHP object when object key unknown but sub key known in the object

Below lists the output of a mySQL query in PHP PDO. The object contains multiple columns from two tables that are then to be combined into a single object.
Some rows in the same table are children of others as identified by the column parent_ID. These children then need to be added to the object of the parent as do their children and so on and so on.
As much as I can achieve this simply for the first two levels of children I cannot see a way without performing another foreach to achieve this beyond the first to layers of the object.
This example should add clarity to the above:
foreach($components as $component){
if($component->parent_ID < 0){
$output->{$component->ID} = $component;
}
else if($output->{$content->parent_ID}){
$output->{$content->parent_ID}->child->{$component->ID} = $component;
}
else if($output->?->child->{$conent->parent_ID}){
$output->?->child->{$content->parent_ID}->child->{$component->ID} = $component;
}
}
Not on the third line there is an ? where there would normally be an ID. This is because we now do not know what that ID is going to be. In the first layer we did because it would be the parent_ID but this line is dealing with the children of children of a parent.
So, as I far I understood from comments and assuming that you don't have a lot of records in DB, it's seems to me the best way is to preload all rows from DB and then build a tree using this function
public function buildTree(array &$objects) {
/** thanks to tz-lom */
$index = array();
$relations = array();
foreach($objects as $key => $object) {
$index[$object->getId()] = $object->setChildren(array());
$relations[$object->getParentId()][] = $object;
if ($object->getParentId()) {
unset($objects[$key]);
}
}
foreach ($relations as $parent => $children) {
foreach ($children as $_children) {
if ($parent && isset($index[$parent])) {
$index[$parent]->addChildren($_children->setParent($index[$parent]));
}
}
}
return $this;
}
P.S. Really, I don't see other way without foreach in foreach. At least, it's not recursive

Finding the children of the sub-sub-category from a sub-category

I currently have a code snippet where for each category, it would find the sub-categories:
$categories = array_map(
function($child)
{
$child['children'] =
$this->getChildren(
$child['id'],
!empty($this->request->get['language_id']) ?
$this->request->get['language_id'] : 1
);
return $child;
}, $categories);
getChildren() would recursively get the children of one category:
private function getChildren($parent_id, $language_id) {
$this->load->model('official/category');
$children =
$this->model_official_category->getCategoriesByParentId(
$parent_id,
$language_id
);
// For each child, find the children.
foreach ($children as $child) {
$child['children'] = $this->getChildren(
$child['id'],
$language_id
);
}
return $children;
}
Currently, using my lambda function within the array_map(), only the sub-category's children would be retrieve, so if each sub-category has its own sub-sub-category, it would not be saved into its children.
How could I show the sub-sub-category given the sub-category we have?
What I wanted to do with my code was to take a parent, get its children, and then treat each of those children as a parent and get its children recursively, however my JSON output does not reflect that. Only the parent has children - the children has no children (despite my database having them).
The problem is that your recursion foreach loop assigns the children that it retrieves to a copy of the child data, rather than the child data itself.
To resolve this you could use foreach loop that references the child data, like so:
foreach ($children as &$child) {
However, due to a number of reasons related to how foreach is implemented internally in PHP (more info if you're interested), it would be considerably more memory efficient to use a for loop instead, as this will avoid quite a few copy-on-write copies of the child data:
for ($i = 0; isset($children[$i]); $i++) {
$children[$i]['children'] = $this->getChildren(
$children[$i]['id'],
$language_id
);
}
This is one place where using objects instead of arrays to represent the child data might be a good idea, because objects are always passed by reference (kind of) and the behaviour would be more like what you were expecting initially.

Yii Framework | Nested arrays in same table

Using CActiveRecord my table looks like this:
A column parent_id has relation many to id, and it works properly.
id | parent_id
---+----------
1 1 <- top
2 1 <- means parent_id with 1 has parent with id=1
3 1
4 2 <- parent for is id=2
5 2
6 2 and so many nested levels....
A goal is how to properly get nested as PHP classically way nested arrays data (arrays inside arrays).
array(1,1) {
array(2,1) {
array(4,2) ....
}
}
Problem is Yii. I didn't find properly way how to pick up a data as nested array using properly CActiveRecord.
What is best way to make nested array results? A main goal is to easy forward to render view so I don't separate with too many functions and calling many models outside from modules or models.
A good is one function to get a result.
Solved using this: Recursive function to generate multidimensional array from database result
You need get a data as arrays from model:
$somemodel = MyModel::model()->findAll();
Then put all in array rather then Yii objects model or what you need:
foreach ($somemodel as $k => $v)
{
$arrays[$k] = array('id' => $v->id, 'parent_id' => $v->parent_id, 'somedata' => 'Your data');
}
Then call a function:
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
Then call put all $arrays data into buildTree function to rebuild nesting arrays data.
$tree = buildTree($arrays);
Now your $tree is nested arrays data.
Note: there aren't depth into function but in convient way you can add using like this sample: Create nested list from Multidimensional Array

Recursive in php

Im doing a project in php CodeIgniter which has a table where all attributes_values can be kept and it is designed such that it can have its child in same tbl. the database structure is
fld_id fld_value fld_attribute_id fld_parent_id
1 att-1 2 0
2 att-2 2 0
3 att-1_1 2 1
4 att-1_2 2 1
5 att-1_1_1 2 3
here above att-1 is the attribute value of any attribute and it has two child att-1_1 and att-1_2 with parent id 1. and att-1_1 has too its child att-1_1_1 with parent_id 3. fld_parent_id is the fld_id of the same table and denotes the child of its. Now i want to show this in tree structure like this
Level1 level2 level3 ..... level n
att-1
+------att-1_1
| +------att-1_1_1
+------att-1_2
att-2
and this tree structure can vary upto n level. the attribute values with parent id are on level one and i extracted the values from level one now i have to check the child of its and if it has further child and display its child as above. i used a helper and tired to make it recursive but it didnt happen. So how could i do it such: the code is below
foreach($attributes_values->result() as $attribute_values){
if($attribute_values->fld_parent_id==0 && $attribute_values->fld_attribute_id==$attribute->fld_id){
echo $attribute_values->fld_value.'<br/>';
$children = get_children_by_par_id($attribute_values->fld_id); //helper function
echo '<pre>';
print_r($children);
echo '</pre>';
}
}
and the helper code is below:
function get_children_by_par_id($id){ //parent id
$children = get_children($id);
if($children->num_rows()!=0){
foreach($children->result() as $child){
get_children_by_par_id($child->fld_id);
return $child;
}
}
}
function get_children($id){
$CI = get_instance();
$CI->db->where('fld_parent_id',$id);
return $CI->db->get('tbl_attribute_values');
}
please help me...............
The key of recursion is an "endless" call. This can be done with a function that calls it self.
So
function get_children($parent_id)
{
// database retrieve all stuff with the parent id.
$children = Array();
foreach($results as $result)
{
$result['children'] = get_children($result['id']);
$children[] = $result;
}
return $children;
}
Or use the SPL library built into PHP already PHP recursive iterator

cakephp Tree behavior remove parent node except children

Is it possible to remove the parent node from a Tree using CakePHP Tree Behavior?. Let's say for example I have a node like this:
<Node A>
- child 1 node A
- child 2 node A
- child 3 node A
- <Node B> (which is also a child 4 of Node A)
- child 1 node B
- child 2 node B
Is it possible to get all the chidren of Node A (using the chidren() or any other function of the Tree behavior in cakePHP), but exclude a node which has children from the result (in our case Node B)?
Any idea please?
Thanks in advance
You can but you'll need to get your hands a bit dirty because I don't think the behavior allows anything like this.
The key is that all nodes that do not have children should have a left and right value that are in sequence. You'll need to whip up a query like this:
SELECT * FROM items WHERE left > (parent's left) AND right < (parent's right) AND right = left + 1 AND parent_id = (parent's ID)
That way we're asking that all returned values are children of our parent and that their left and right values are in sequence, which they won't be if a node has children.
Looking at specifications there is no specific method for this, so you must build your own function for that using children() and childCount(). Here's the code template (I don't use Cake PHP):
$children = <call TreeBehavior children() method with $id = id of Node A and $direct = true>;
$children_without_children = array();
foreach ($children as $child) {
if (<call TreeBehavior childCount() method with $id = $child->id and $direct = true> === 0) {
$children_without_children[] = $child;
}
}
Then $children_without_children should contain what you want.
you can use this code:
$this->Node->removeFromTree($id, true);
here is code from my cakephp 2.x project:
public function delete($id = null) {
$this->ProductCategory->id = $id;
if (!$this->ProductCategory->exists()) {
throw new NotFoundException(__('Invalid product category'));
}
$this->request->allowMethod('post', 'delete');
if ($this->ProductCategory->removeFromTree($id, TRUE)) {
$this->Session->setFlash(__('The product category has been deleted.'));
} else {
$this->Session->setFlash(__('The product category could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
Using this method (e.i. removeFromTree ()) will either delete or move a node but retain its sub-tree, which will be reparented one level higher. It offers more control than delete, which for a model using the tree behavior will remove the specified node and all of its children.

Categories