【问题标题】:Codeigniter recursive get all idsCodeigniter递归获取所有ID
【发布时间】:2013-08-13 22:17:51
【问题描述】:

我想从 1 个表中获取所有带有递归的 ID。我设法回显了这些变量,但是当我尝试将其放入数组时失败了。这是字符串版本:

public function get_numProducts($cid)
{
    $this->db->select('cat_id');
    $this->db->from('ci_categories');
    $this->db->where('cat_child',$cid);
    $q = $this->db->get();

    $result = $q->result();

    $i=0;
    $a="";
    foreach($result as $mainCategory)
    {
        $a .= $mainCategory->cat_id;
        $a .= $this->get_numProducts($mainCategory->cat_id);
    }

    return $a;

}

当使用参数“4”调用此函数时,我得到字符串输出:89。这很好。但我想输出一个数组(4,8,9)。感谢您的帮助

编辑:

第二版

public function get_numProducts($cid)
{
    $this->db->select('cat_id');
    $this->db->from('ci_categories');
    $this->db->where('cat_child',$cid);
    $q = $this->db->get();

    $result = $q->row();
    $n = $q->num_rows();

    if ($n > 0)
    {
        $array[] = $result->cat_id." ";
        $array[] = $this->get_numProducts($result->cat_id);
    }


    return $array;

}

此版本返回多维数组:

array (size=2)
  0 => string '8 ' (length=2)
  1 => 
    array (size=2)
      0 => string '9 ' (length=2)
      1 => null

【问题讨论】:

    标签: php codeigniter loops recursion


    【解决方案1】:

    您必须将数组作为对函数每次迭代的引用..

    public function get_numProducts($cid, &$array)
    

    ..

    $array[] = $cid;
    
    if ($n > 0) $this->get_numProducts($result->cat_id, $array);
    

    【讨论】:

    • 工作正常。但是我如何将第一个值“4”设置为该数组的起始值?
    猜你喜欢
    • 2011-08-21
    • 2020-11-26
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 2020-03-22
    • 2011-04-12
    • 2013-05-15
    相关资源
    最近更新 更多