当前位置:Gxlcms > PHP教程 > php变量名中有变量

php变量名中有变量

时间:2021-07-01 10:21:17 帮助过:2人阅读

$a = array(
    array(
        'name' => 'lang',
        'user' => '0',
        'value' => 'zh-CN'
        ),
    array(
        'name' => 'charset',
        'user' => '22',
        'value' => 'UTF-8'
        ),
);

想在页面以 $site['lang'] 输出 zh-CN,$site['charset'] 输出 UTF-8

我的错误写法,求写法

foreach ($a as $opt) {
    foreach ($opt as $key => $value) {
        if ($key == 'name') {
            $key_name = $value;
        }
        if ($key == 'value') {
            $key_value = $value;
        }
    }
    $site = 'site[\''. $key_name .'\']';
    $$site = $key_value;
}

回复内容:

$a = array(
    array(
        'name' => 'lang',
        'user' => '0',
        'value' => 'zh-CN'
        ),
    array(
        'name' => 'charset',
        'user' => '22',
        'value' => 'UTF-8'
        ),
);

想在页面以 $site['lang'] 输出 zh-CN,$site['charset'] 输出 UTF-8

我的错误写法,求写法

foreach ($a as $opt) {
    foreach ($opt as $key => $value) {
        if ($key == 'name') {
            $key_name = $value;
        }
        if ($key == 'value') {
            $key_value = $value;
        }
    }
    $site = 'site[\''. $key_name .'\']';
    $$site = $key_value;
}

//if your php version >= 5.5
$site = array_column($a, 'name', 'value');

//else
$site = array();
foreach($a as $t) $site[$t['name']] = $t['value'];

人气教程排行