从foreach循环返回数组

时间:2018-02-25 02:37:36

标签: php codeigniter

public function get_inner_refs($referral){

    $query = $this->db->query("SELECT username FROM users WHERE binery_referral='$referral'");
        if ($query->num_rows() > 0) {

            foreach ($query->result_array() as $row){
                $referral = $row['username'];

                $referrals[] =  $row['username'];
                $this->get_inner_refs($referral, $referrals);
            }

        }   
        return $referrals;
    }

这里我想返回所有用户的数组,但它只返回数据库中的第一个值,

2 个答案:

答案 0 :(得分:0)

尝试创建一个private变量来分配并创建一个get方法:

private $referrals;

public function get_inner_refs($referral)
{
    $query = $this->db->query("SELECT username FROM users WHERE binery_referral='$referral'");
        if ($query->num_rows() > 0) {
            foreach ($query->result_array() as $row){
                $username = $row['username'];
                $this->referrals[] = $username;
                $this->get_inner_refs($username);
            }
        }

        return $this;
    }

public function getReferrals()
{
    return $this->referrals;
}

然后使用:

$referrals = $ReferralClass->get_inner_refs($username)->getReferrals();

答案 1 :(得分:0)

我认为你可以像这样编辑

public function get_inner_refs($referral='',$referrals = []){

    $query = $this->db->query("SELECT username FROM users WHERE binery_referral='$referral'");
        if ($query->num_rows() > 0) {

            foreach ($query->result_array() as $row){
                $referral = $row['username'];

                $referrals[] =  $row['username'];
                $this->get_inner_refs($referral, $referrals);
            }

        }   
        return $referrals;
    }