简体   繁体   中英

PHP append a key => value pair to an array

So I'm using a foreach cycle like this:

foreach($cats_arr as $category) {
    $options_arr[$category->name] = false;
}

and when I var_dump($options_arr['Articles']) it comes out like this, so I assume that I'm building the array properly:

bool(false) string(1) "5"

Next, I need to assign that array as a value of a key-value pair in another array, and then it breaks. I'm doing it like this:

$admin_options = array(
"cats" => $options_arr
);

So I can access the array with $admin_options['cats'], but how to I access the array's keys that's assigned to the "cats" key?

EDIT: Here's what comes out when I var_dump($admin_options['cats'])

array(1) { [0]=> array(4) { ["Articles"]=> bool(false) ["Blog Posts"]=> bool(false) ["News"]=> bool(false) ["Uncategorized"]=> bool(false) } }

Your $options_arr contains multiple keys, so you will have to either specify the key or use a foreach loop:

// Echo first key
echo $admin_options['cats'][0]['Articles'];

// Or this for all the keys
foreach($admin_options['cats'] as $cat) {
    echo $cat['Articles'];
}

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