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
Related
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
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.
I have a nested list of categories which DB looks something like this:
id parent_id title
83 81 test3
86 83 test1
87 83 test2
94 87 subtest2.1
95 87 subtest2.2
...etc...
I need to add all child element ids into the $checked_elements array of each parent id.
So if some specific id is selected, it's automatically added into the array of $checked_elements. Here how it looks like:
I'am stuck with the recursive function, on how to add recursively child items of each parent item id ? My function won't go deeper then the 2nd level, can anyone tell me how to work it out so it will check for all child items ?
private function delete( ){
// Collect all checked elements into the array
$checked_elements = $this->input->post('checked');
// Recursive function to check for child elementts
foreach( $checked_elements as $key => $value ){
// Get records where parent_id is equal to $value (checked item's id)
$childs = $this->categories_model->get_by(array('parent_id' => $value));
// Add found record's id into the array
foreach( $childs as $child ){
$checked_elements[] => $child->id;
}
}
}
You can try passing the accumulator array around by reference:
function collect($ids, &$items) {
foreach($ids as $id){
$items[] = $id;
$childs = $this->categories_model->get_by(array('parent_id' => $id));
collect(array_column($childs, 'id'), $items);
}
return $items;
}
function delete( ){
$items = array();
collect($this->input->post('checked'), $items);
//... delete $items
}
In php 5.5+ you can also use generators in a way similar to this:
function collect($ids) {
foreach($ids as $id) {
yield $id;
$childs = $this->categories_model->get_by(array('parent_id' => $id));
foreach(collect(array_column($childs, 'id')) as $id)
yield $id;
}
function delete( ){
$ids = collect($this->input->post('checked'));
I assume your tree is rather small, otherwise I'd suggest a more efficient approach, like nested sets.
If your php version doesn't support array_column, you can use this shim.
Here's how I'm getting my data from database. It is a 3 level hierarchy. Parent, child and children of child.
page_id | parent_id
1 0
2 1
3 0
4 3
The top data shows 0 as the parent.
$id = 0;
public function getHierarchy($id)
{
$Pages = new Pages();
$arr = array();
$result = $Pages->getParent($id);
foreach($result as $p){
$arr[] = array(
'title' => $p['title'],
'children' => $this->getHierarchy($p['page_id']),
);
}
return $arr;
}
So far I'm getting data but it's kinda slow. The browser loads so long before showing the data. How can I make my code faster so it does not take long for the browser to load data?
Thanks.
You have multiple options to speed it up:
Select all rows from table and do the recursion only on the PHP
side. It's only an option if there are not too many rows in table.
You can self join the table. This is a nice option if you know that there are no more levels of hierarchy in the future. Look at the post: http://blog.richardknop.com/2009/05/adjacency-list-model/
Use nested sets: http://en.wikipedia.org/wiki/Nested_set_model
Or my favorite: Closure Table
Use some kind of caching. You could cache the db queries or the whole tree menu html or the PHP array for example.
Caching example:
Caching you can do in normal files or use specialized api's like memcache, memcached or apc.
Usually you have a class with 3 basic methods. An interface could look like:
interface ICache
{
public function get($key);
public function set($key, $value, $lifetime = false);
public function delete($key);
}
You can use it like:
public function getHierarchy($id)
{
$cached = $this->cache->get($id);
if (false !== $cached) {
return $cached;
}
// run another method where you build the tree ($arr)
$this->cache->set($id, $arr, 3600);
return $arr;
}
In the example the tree will be cached for one hour. You also could set unlimited lifetime and delete the key if you insert another item to the db.
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