Cnab
Cnab

Reputation: 49

get only child id from multi level array in PHP

I have multi level categories array. i only want to get child ID's, if parent don't have child. then return that parent id as well

id   parent_id    name
1      0          fashion
2      1          women
3      1          men
4      2          jeans
5      2          skirts
6      5          short skirts
7      5          long skirts
8      0          Home & entertainment

I tried this fucntion.

function buildtree($src_arr, $parent_id = 0, $tree = array()){
       foreach($src_arr as $idx => $row){
           if($row['parent_id'] == $parent_id){
               foreach($row as $k => $v)
                   $tree[$row['id']][$k] = $v;
               unset($src_arr[$idx]);
               $tree[$row['id']]['children'] = self::buildtree($src_arr, $row['id']);
           }
       }
       ksort($tree);
       return $tree;
   }

But it also gives me all parents id's.

desired outcome with id ( i am typing name for easy understanding)

array(
 [0]  = men 
 [1]  = jeans
 [2]  = short skirts
 [3]  = long skirts
 [4]  = home & entertainment 
)

Thanks for help.

Upvotes: 1

Views: 1298

Answers (2)

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

A simple where clause with not in logic will help you select the children, then the parents that have no children.

select c.id, c.name
from categories c
where c.id not in (select parent_id from categories order by id desc)

Which gives a result set of

+----+----------------------+
| id | name                 |
+----+----------------------+
|  3 | men                  |
|  4 | jeans                |
|  6 | long skirts          |
|  7 | short skirts         |
|  8 | home & entertainment |
+----+----------------------+
5 rows in set

See SQL Fiddle

Upvotes: 3

clemens321
clemens321

Reputation: 2098

Done in PHP you can use this function, which gives you a flat array with all edge childs based on a given parent_id. If you want to check a whole database table sql-only is the better option.

function getchildren($src_arr, $parent_id = 0) 
{ 
    $allchildren = array();

    foreach($src_arr as $idx => $row){ 
        if($row['parent_id'] == $parent_id){ 
            $children = static::getchildren($src_arr, $row['id']);
            if ($children) { 
                $allchildren = array_merge($allchildren, $children);                 
            } else { 
                $allchildren[] = $row;
            } 
        } 
    } 

    return $allchildren;
} 

Upvotes: 0

Related Questions