简体   繁体   中英

How do I add new elements to this type of array?

I am wondering what I have to do to add something to:

$setting = array(
    'element' => array(
        array(
            'elelemt_name' => '',
            'element_path' => ''
        ),
    )
);

The object I want to add is:

    array(
        'elelemt_name_two' => '',
        'element_path_two' => ''
    ),

the end result would be:

$setting = array(
    'element' => array(
        array(
            'elelemt_name' => '',
            'element_path' => ''
        ),
        array(
            'elelemt_name_two' => '',
            'element_path_two' => ''
        ),
    ),
);

The catch: $setting = array(); could be $a = array(); or $b = array() or anything, So I have no idea how I would add something when the variable containing the array could named anything.

What I do know, is that the first key, $element, will always be $element. So that part can be hard coded.

I was thinking of writing a function like:

function add_array($type, $array){
    if(is_array($array) && is_array($type)){
        array_push($type, $array);
    }
}

Then I could call it as such:

$array = array(
    'element_name_two' => '',
    'element_path_two' => ''
)

add_array($setting['element'], $array);

does this make sense? or am I doing it wrong?

No need for heavy artillery:

$setting['element'][] = $new_array;
                   ^^--- short-hand syntax for array_push()

The easiest way is just to add it.

$setting['element'][] = array('element_name_two' => '','element_path_two' => '');

If you want a function to adjust the contents of an array you should pass in the array by reference.

function add_array(&$type, $array){
    if(is_array($array) && is_array($type)){
        array_push($type, $array);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM