简体   繁体   中英

How to create array in PHP with strings from another array as position names?

Basically what I'm trying to do is create an array that has strings for their position names, such as:

$types = [
    "Methods" => array(),
    "Systems" => array(),
    "Equipment" => array()
]

This is what var_dump($types) results in:

array(3) { ["Methods"]=> array(0) { } ["Systems"]=> array(0) { } ["Equipment"]=> array(0) { } } 

However, instead of declaring $types like this, I want to have an array $list ...

$list = ['Foo', 'Bar', 'Baz', ...];

...that generates an array $types ...

$types = ["Foo" => array(), "Bar" => array(),"Baz" => array(), ...]

Is it possible? I have tried doing array_push($types, $list) but that just copies the the string array into the last position of $types

使用array_fill_keys函数

$types = array_fill_keys($list, []);

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