我正在嘗試創建包含資料庫中所有父子 ID 的單個陣列。但我得到的只是單一資料。
我的理想輸出是:
array('160', '161', '162', '163', '164');
我得到的只是
array('160');
這是我到目前為止所做的。
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));
和我在這里獲取的資料:
tbl_policies

構建問題對我來說有點困難。因此,如果有不清楚的地方,請在下面發表評論,我會盡力使其更易于理解。提前致謝。
uj5u.com熱心網友回復:
我了解,您想洗掉一個父級及其所有子級和孫子級。但是您不是直接按順序執行此操作,而是希望收集要洗掉的記錄的所有 id。您應該執行以下步驟:
- Parent-Id(示例 160)是已知的。將此添加到您的串列中。
- 撰寫一個遞回函式,例如 getChildrenIds(parentId)。
- 在這個函式中,你應該迭代孩子。如果孩子有標志“isArray”(根據您的應用程式邏輯),那么您應該呼叫 getChildrenIds(currentChildId)
我寫了以下功能。它應該作業。
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);
}
請注意,$where_in 通過參考傳遞給遞回函式 getChildrenIds() 并填充在那里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440663.html
