Home > Enterprise >  How to create an array from single table data with parent and child included?
How to create an array from single table data with parent and child included?

Time:11-13

I have data in a table something like in this image. In this example, 87 is the main parent which have child category 92, 97, 100. Each child can also have sub categories.

Data

This is my code so far I have tried, but I am not able implement level 3 of the array.

    public function getList(int $id): array
{
    $finalArray = [];

    foreach ($result as $key => $value) {
        if ($value['parent_id'] === '87') {
            $finalArray[$value['id']] = [
                'title' => $value['title'],
                'subCategory' => []
            ];
            continue;
        }
        // Extract parent
        $parentId = $value['parent_id'];
        if ($this->multiKeyExists($finalArray, $parentId)) {
            $finalArray[$parentId]['subCategory'] = [
                'title' => $value['title'],
                'subCategory' => []
            ];
        }
    }
}

protected function multiKeyExists(array $arr, $key)
{
    if (array_key_exists($key, $arr)) {
        return true;
    }
    foreach ($arr as $element) {
        if (is_array($element) && $this->multiKeyExists($element, $key)) {
            return true;
        }
    }

    return false;
}

Expected result:

- 92
  - 93
     - 95
  -96

enter image description here

Can anyone help me with a simple way to solve the problem ?

CodePudding user response:

function sortResult($result,$id=87){
   $finalArr=[];
   $finalArr['id']=$id;
    foreach($result as $key=>$val){
        if($val['id']==$id){
            $finalArr['title']=$val['title'];
        }
        if($val['parent_id']==$id){
            $finalArr['subs'][$val['id']]=sortResult($result,$val['id']);
        }
    }
    return $finalArr;
}

CodePudding user response:

The recursive function will look for a child and run itself

$createtree = function ($start = NULL) use ($result,&$createtree){
    $start = $start ?? 0;
    $part = $result[$start];
    //has childs?
    if($key = array_keys(array_column($result, 'parent_id'),$part['id'] )){
         $part['sub'] = array_map(function($val) use ($result,&$createtree) { 
             return $createtree($val);
             },$key);
         
    }
    return $part;
   
    
};
print_r($createtree());
  •  Tags:  
  • php
  • Related