Home > Mobile >  How to create single array of id's from parent and child array
How to create single array of id's from parent and child array

Time:03-12

I'm Trying to create single array that contains all the ID of parent and child from the database. But all I was getting is single data.

My ideal output is:

array('160', '161', '162', '163', '164');

what am I getting is only

array('160');

Here is what I've done so far.

public function arrayId(array $elements) {
    $where_in = array();
    foreach($elements as $element){
        if($element->isArray) {
            $elems = $this->my_model->select_where('tbl_policies', array('parent_id' => $element->id));
            $this->arrayId($elems);
        }
        $where_in[] = $element->id;
   }
   return $where_in;
}
$id = 160; //for instance
$elements = $this->my_model->select_where('tbl_policies', array('id' => $id));
$where_in = $this->arrayId($elements);
                    
die(print_r($where_in));

and the data I'm fetching here: tbl_policies enter image description here

It's kinda difficult for me to construct questions. So please if something is not clear, do comment below, I'll try my best to make it more understandable. Thanks in advance.

CodePudding user response:

I understand, that you want to delete a parent with all its children and grandchildren. But you do it not directly and sequentially rather want to collect all ids of the records to be deleted. You should go following steps:

  1. Parent-Id (example 160) is already known. Add this to your list.
  2. Write a recursive function such as getChildrenIds(parentId).
  3. Within this function you should iterate over children. And if a child has the flag "isArray" (according to your application logic) then you should call getChildrenIds(currentChildId)

I have written following function. It should work.

    public function getChildrenIds( int $parentId, array &$idList) {

    $idList[] = $parentId;
    $records = $this->my_model->select_where('tbl_policies', array('parent_id' => $parentId));
    foreach($records as $r){
        if($r->isArray)
            $this->getChildrenIds($r->id, $idList);
        else
            $idList[] = $r->id;
    }
    return;
}

public function CollectIds(){   
    $id = 160; //for instance
    $where_in = array();     
    $this->getChildrenIds($id, $where_in);
}

Please notice, that $where_in passed by reference to the recursive function getChildrenIds() and filled there.

  • Related