在 CodeIgniter 中,我正在尝试创建一个函数。需要创建将删除数据库中的行的数组,例如:
$selected_items_by_id = array('1','2','3','4',);   // --<<<Need Create This
$this->db->where_in('id', $selected_items_by_id);
$this->db->delete('mytable');
mytabe数据库结构:
ID | NAME         | PARENT_ID
1   Item1              0     // First Root item
2   Item2              1     // First Root sub item
3   Item3              2     // First Root sub sub item
4   Item4              3     // First Root sub sub sub item
5   Item5              0     // Second Root item
物品布局:
Item1
+Item2
++Item3
+++Item4
Item5
在这里,我得到了所需的项目 ID(来自选择框):
$id = $this->input->post('delete_menu_item');
逻辑:
- 如果 item parent_id == 0,则 item 是 root。
- 如果 Item 是根项,则数组中将只有根项 id
- 在数组中需要 $id 和所有 $id 子(如果它们存在)
更新 我尝试在 CI 之外创建递归函数。
搜索功能 - 分离必要的子阵列:
 function search($array, $key, $value)
{
    $results = array();
    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;
        foreach ($array as $subarray)
            $results = array_merge($results, search($subarray, $key, $value));
    }
    return $results;
}
我正在使用这个数组,基于 DB 条目:
$array = array(
array('id' => '1', 'name' => 'Item1', 'parent_id' => '0'),
array('id' => '2', 'name' => 'Item2', 'parent_id' => '1'),
array('id' => '3', 'name' => 'Item3', 'parent_id' => '2'),
array('id' => '4', 'name' => 'Item4', 'parent_id' => '3'),
array('id' => '5', 'name' => 'Item5', 'parent_id' => '0'),
);
递归函数:
function build_array($array,$id, $final = NULL){
   $data = search($array, 'id', $id);
   foreach ($data as $item):
       if ($item['parent_id'] == 0){
           $final[] = $item['id'];
       }
       else {    
           $parent_id = $item['parent_id'];
           $final[] = $item['id'];
           $final[] = $parent_id;
          build_array($array, $parent_id, $final); 
           // Here go recursive
       }    
   endforeach;
        return $final;
}
$result = build_array($array,1);
var_dump($result);
递归函数应该是什么?