值不会动态添加到数组

时间:2018-05-21 05:15:15

标签: php arrays codeigniter

在CodeIgniter中,我想从两个不同的函数向数组添加值,但这些值仅在第一个函数内添加到数组中。请告诉我们可能出现什么问题?

代码:

public $ChnCat_tags = array();
function first_function() {
    //some code 
    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );
    $recursion_result = second_function($ChnCat_tags);
    return $ChnCat_tags; //only returns values added inside first_function
}

function second_function($ChnCat_tags) {
    //some code
    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );
    recursion_result = second_function($ChnCat_tags);
    return recursion_result;
}

2 个答案:

答案 0 :(得分:2)

您可以在任何地方开始使用$this->ChnCat_tags而不只是ChnCat_tags

或(pass by reference):

function first_function() {
    //some code 
    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );
    second_function($ChnCat_tags);
    return $ChnCat_tags;
}

function second_function(&$ChnCat_tags) {
    //some code
    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );
    second_function($ChnCat_tags);
    // no need to return now
    //return recursion_result;
}

答案 1 :(得分:0)

喜欢这个

function first_function() {

    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );

    # Must call function with $this
    $recursion_result = $this->second_function($ChnCat_tags); 

    # print the value of $recursion_result whish hold entire data
    print_r($recursion_result); 
}

function second_function($ChnCat_tags) {

    $ChnCat_tags[] = array(
        'level' => $level,
        'value' => $row_vct->id_vct,
        'label' => $row_vct->displayname_vct,
        'disable' => $disb
    );
    # just return the array data.
    return $ChnCat_tags;
}