recursive function to get all the child categories
I had a hard time trying to figure out your function. I think this will do what you want. It gets all the children of a category with ID $id, and also their children (thus getting the whole sub category, sub sub category effect that you wanted).
function categoryChild($id) {
$s = "SELECT ID FROM PLD_CATEGORY WHERE PARENT_ID = $id";
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
# It has children, let's get them.
while($row = mysql_fetch_array($r)) {
# Add the child to the list of children, and get its subchildren
$children[$row['ID']] = categoryChild($row['ID']);
}
}
return $children;
}
This function will return:
$var = array(
'categoryChild ID' => array(
'subcategoryChild ID' => array(
'subcategoryChild child 1' => array(),
'subcategoryChild child 2' => array()
)
),
'anotherCategoryChild ID' => array() # This child has no children of its own
);
It basically returns an array with the ID of the child and an array containing the IDs of its children. I hope this is of any help.
PHP recursive function to retrieve all children of a category
function get_categories($parent = 0)
{
$html = '<ul>';
$query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
while($row = mysql_fetch_assoc($query))
{
$current_id = $row['category_id'];
$html .= '<li>' . $row['category_name'];
$has_sub = NULL;
$has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
if($has_sub)
{
$html .= get_categories($current_id);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
print get_categories();
Find all Child categories recursively from and Array - PHP
Try this one
public function get_all_child_categories($cat_id, $all_child = array()) {
global $all_categories_details;
foreach ($all_categories_details as $cat){
if($cat->parent_category_id == $cat_id){
$all_child[] = $cat->inv_category_id;
$all_child = self::get_all_child_categories($cat->inv_category_id, $all_child);
}
}
return $all_child;
}
Recursively get all children
assuming that each category only ever has one child
edited to adhere to the expected result...
function iterChildren(cat) {
let c = cat, children = [];
while (c.child) {
children.push({id: c.child.id});
c = c.child;
}
return {id: cat.id, children: children};
}
let newData = data.map(iterChildren);
PHP Recursive Function to Retrieve List of Sub Categories
You seem to want a simple one-dimensional array (eg. a list) with the sub-category-ids, what you're currently building is a tree (nested arrays). This should to the trick:
public function getList($parentId)
{
$retVal = array($parentId);
$query = "SELECT * FROm `bs_category` WHERE `parent_id` = ".$parentId;
$result = $this->db->query($query);
foreach($result->rows as $row)
{
$retVal = array_merge($retVal, $this->getList($row["category_id"]));
}
return $retVal;
}
Recursively obtain all children from a single parent
Rather than make it recursive, you can expand the check to check for all of the so far found parent nodes(using in_array()
. This makes it a one pass check..
public function getChildrenIds($folders, $parent_id)
{
// Prime array with parent looking for
$folderIds = [$parent_id];
foreach($folders as $folder) {
// Check if matches any parent so far found
if( in_array($folder['parent'], $folderIds) ) {
$folderIds[] = $folder['id'];
}
}
// Remove parent id added at start
array_shift($folderIds);
return $folderIds;
}
Find all middle categories from nth child to top level in PHP recursion
i don't know if you are using mysqli or PDO so i wrote the code on basics...
<?php
$cats = [];
function find_parent($parent_id){
global $cats;
if ($parent_id > 0){
$q = mysql_query('SELECT cat_pid FROM Category WHERE cat_id = ' . $parent_id);
$r = mysql_result($q, 0, 'cat_pid');
if ($r > 0){
$cats[] = $parent_id;
find_parent($r);
}
}
}
find_parent(4);
array_shift($cats); //it adds first record too and i think you don't want so removing it here...
print_r($cats);
Get All Children to One List - Recursive C#
You can do SelectMany
List<Location> result = myLocationList.SelectMany(x => x.Children).ToList();
You can use where condition for some selective results like
List<Location> result = myLocationList.Where(y => y.ParentID == someValue)
.SelectMany(x => x.Children).ToList();
If you only required Id's of Children you can do
List<long> idResult = myLocationList.SelectMany(x => x.Children)
.SelectMany(x => x.ID).ToList();
Get all parents and children of a tree recursively
First define the relationships in your model
public function children() {
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function parent() {
return $this->belongsTo(Category::class, 'parent_id', 'id');
}
Then in your view, I don't know how many sub levels you have. But there are 2 ways:
1- The easiest way
If you know, you will never go over 3 levels, just nest 3 foreach in your view
First you query eagerly
$categories = Category::with('children')->get(); //save you some queries
@foreach($categories as $category)
@if( $category->children )
@foreach($category->children as $level2)
@if($level2->children)
@foreach($level2->children as $level3)
@if($level3->children)
//another foreach
@endif
{{ $level3->title }}
@foreach
@endif
{{ $level2->title }}
@endforeach
@endif
{{ $category->title }}
@endforeach
2- The actual recursive way.
This is experimental and not tested
Define a recursive relationship
public function recursiveChildren() {
return $this->children()->with('recursiveChildren');
//It seems this is recursive
}
Returning All values Found from Recursive Function PHP
IMO there are two good ways to solve situations like this.
Option 1
Adjust the return values to arrays only, and add every recursive step to the beginning or end of the array. Your code would look like this (with the unrelated stuff redacted):
private function get_parent_category( $category_id ) {
<shortened>
if( $parent_category->parent == 0 ):
return [$parent_category];
else:
$found = $this->get_parent_category( $parent_category->id );
array_unshift( $found , $parent_category ); //or array_push
return $found;
endif;
<shortened>
Option 2
Or you can pass the end result by reference and fill it on the way down. This would look like this; you don't need explicit returns:
private function get_parent_category( $category_id , &$found) {
<shortened>
if( $parent_category->parent == 0 ):
$found[] = $parent_category;
else:
$this->get_parent_category( $parent_category->id , $found );
$found[] = $parent_category;
endif;
<shortened>
Some people have a strong opinion on which way is better, but in my opinion you can pick the one you like.
Related Topics
Warning: "Continue" Targeting Switch Is Equivalent to "Break". Did You Mean to Use "Continue 2"
PHP - Time Remaining Until Specific Time from Current Time of Page Load
Unescape or HTML Decode in Twig (PHP Templating)
Preg_Match() VS Strpos() for Match Finding
Replace Ereg_Replace with Preg_Replace
Paypal Gateway Has Rejected Request. Security Header Is Not Valid (#10002: Security Error Magento
How to Append to a Xml File with PHP Preferably with Simplexml
PHP Strtotime +1 Month Adding an Extra Month
PHP - Replace Colour Within Image
Which Method Is Preferred Strstr or Strpos
PHP Soap Client for Uk Mail Webservice API
How to Include File Outside Document Root
In PHP, How to Get the First and Last Date of a Month
Detecting File Upload Size on the Client Side
Regular Expression and Forward Slash
The Requested Url /Projectname/Users Was Not Found on This Server. Laravel