2 回答
TA贡献1843条经验 获得超7个赞
您可以遍历数组并创建一个变量。
$sitearray = [
'pocb', 'diario', 'mlp', 'watch', 'music', 'games', 'fb', 'tt',
'tasks', 'years', '2018', '2019', '2020', 'stories', 'nw', 'pequenata',
'spaceliving', 'nazzevo', 'ls', 'mf', 'wt', 'stake2', 'textmaker', 'thingsido'
];
foreach($sitearray as $value) {
${"site$value"} = $value;
}
print_r($GLOBALS);
然后变量在当前范围内。(缩短输出)
[sitepocb] => pocb
[sitediario] => diario
[sitemlp] => mlp
[sitewatch] => watch
[sitemusic] => music
[sitegames] => games
[sitefb] => fb
[sitett] => tt
[sitetasks] => tasks
[siteyears] => years
[site2018] => 2018
[site2019] => 2019
[site2020] => 2020
[sitestories] => stories
[sitenw] => nw
[sitepequenata] => pequenata
[sitespaceliving] => spaceliving
[sitenazzevo] => nazzevo
[sitels] => ls
[sitemf] => mf
[sitewt] => wt
[sitestake2] => stake2
[sitetextmaker] => textmaker
[sitethingsido] => thingsido
所以如果你echo $sitethingsido;会得到
事物
TA贡献1829条经验 获得超7个赞
如果我正确理解了这个问题,一种可能的方法是这样的:
<?php
$sitearray = array(
'pocb',
'diario',
'mlp',
'watch',
'music',
'games',
'fb',
'tt',
'tasks',
'years',
'2018',
'2019',
'2020',
'stories',
'nw',
'pequenata',
'spaceliving',
'nazzevo',
'ls',
'mf',
'wt',
'stake2',
'textmaker',
'thingsido',
);
$sites = array();
$i = 0;
while ($i <= count($sitearray) - 1) {
// Generate variable & key name
$site_key = 'site_' . $sitearray[$i];
// Fill $sites array
$sites[$site_key] = $sitearray[$i];
// Create auto-generated variables like '$site_textmaker'
$$site_key = $sitearray[$i];
$i++;
}
var_dump($sites); /* -->
array(24) {
["site_pocb"] => string(4) "pocb"
["site_diario"] => string(6) "diario"
["site_mlp"] => string(3) "mlp"
["site_watch"] => string(5) "watch"
["site_music"] => string(5) "music"
["site_games"] => string(5) "games"
["site_fb"] => string(2) "fb"
["site_tt"] => string(2) "tt"
["site_tasks"] => string(5) "tasks"
["site_years"] => string(5) "years"
["site_2018"] => string(4) "2018"
["site_2019"] => string(4) "2019"
["site_2020"] => string(4) "2020"
["site_stories"] => string(7) "stories"
["site_nw"] => string(2) "nw"
["site_pequenata"] => string(9) "pequenata"
["site_spaceliving"] => string(11) "spaceliving"
["site_nazzevo"] => string(7) "nazzevo"
["site_ls"] => string(2) "ls"
["site_mf"] => string(2) "mf"
["site_wt"] => string(2) "wt"
["site_stake2"] => string(6) "stake2"
["site_textmaker"] => string(9) "textmaker"
["site_thingsido"] => string(9) "thingsido"
}
*/
var_dump($sites['site_' . $sitearray[2]]); // -> string(3) "mlp"
var_dump($site_textmaker); // -> string(9) "textmaker"
?>
site_前缀(而不是site在问题中使用)用于提高可读性。您可以自由更改它。
- 2 回答
- 0 关注
- 119 浏览
添加回答
举报