Home > Backend Development > PHP Tutorial > php变量名中有变量

php变量名中有变量

WBOY
Release: 2016-06-06 20:40:44
Original
968 people have browsed it

<code>$a = array(
    array(
        'name' => 'lang',
        'user' => '0',
        'value' => 'zh-CN'
        ),
    array(
        'name' => 'charset',
        'user' => '22',
        'value' => 'UTF-8'
        ),
);
</code>
Copy after login
Copy after login

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

我的错误写法,求写法

<code>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;
}
</code>
Copy after login
Copy after login

回复内容:

<code>$a = array(
    array(
        'name' => 'lang',
        'user' => '0',
        'value' => 'zh-CN'
        ),
    array(
        'name' => 'charset',
        'user' => '22',
        'value' => 'UTF-8'
        ),
);
</code>
Copy after login
Copy after login

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

我的错误写法,求写法

<code>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;
}
</code>
Copy after login
Copy after login

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

//else
$site = array();
foreach($a as $t) $site[$t['name']] = $t['value'];
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template