简体   繁体   中英

Add new “col” to an existing two-dimensional array

I have a two-dimensional array:

$arr= array();
array_push($arr, array('col1' => 'someval', 'col2' => 'someval'));
array_push($arr, array('col1' => 'someval', 'col2' => 'someval'));

Now I want to add a new "col" to each 2nd level array like 'col3' => 'someval' . How to do that?

Use [] notation to add a value with key key :

foreach ($arr as &$item) { 
    $item['col3'] = 'value'; 
}

Use & with $item so as pass each array of $arr by reference.

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