简体   繁体   中英

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

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 在此处输入图像描述

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM