php 变量到数组 - 与“提取”相反

发布于 2025-01-07 20:28:35 字数 415 浏览 0 评论 0原文

PHP 有一个函数 extract 可以将数组转换为:

$array = array(
 'var1' => 1,
 'var2' => 2
);

到:

$var1 = 1;
$var2 = 2;

现在,我需要相反的,我有几个变量:

$var3 = 'test';
$test = 'another';
$datax = 1;

需要是:

$array = array(
 'var3' => 'test',
 'test' => 'another',
 'datax' => 1
);

PHP 中有类似的东西吗?

PHP has a function extract that will convert an array like this:

$array = array(
 'var1' => 1,
 'var2' => 2
);

to:

$var1 = 1;
$var2 = 2;

now, I need the opposite, i have few variables:

$var3 = 'test';
$test = 'another';
$datax = 1;

that needs to be:

$array = array(
 'var3' => 'test',
 'test' => 'another',
 'datax' => 1
);

Is there something like this in PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

污味仙女 2025-01-14 20:28:35

您可以使用compact()来实现这一点。

$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');

参考:http://php.net/manual/en/function.compact.php

You can use compact() to achieve this.

$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');

Reference: http://php.net/manual/en/function.compact.php

夏见 2025-01-14 20:28:35

像这样

$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);

like this

$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);
情绪 2025-01-14 20:28:35
$array = get_defined_vars()

请参阅get_define_vars()

$array = get_defined_vars()

See get_defined_vars()

逐鹿 2025-01-14 20:28:35

您必须真的确定您想要执行此操作(它自动包含全局范围内的内容),但您可以使用

$my_vars = get_defined_vars();

如果您希望它比这更有选择性,您可以考虑像这样过滤它这:

$my_vars = pack_vars(get_defined_vars())

function pack_vars ($defined_vars)
{
    $packed = array();
    $ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');

    foreach ($defined_vars AS $key => $value)
    {
        if (!in_array($key, $ignored))
        {
            $packed[$key] = $value;
        }
    }
    return $packed;
}

You'd have to be really sure you wanted to do this (it includes things in the global scope automatically) but you can use

$my_vars = get_defined_vars();

If you want it more selective than that, you could look at filtering it like this:

$my_vars = pack_vars(get_defined_vars())

function pack_vars ($defined_vars)
{
    $packed = array();
    $ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');

    foreach ($defined_vars AS $key => $value)
    {
        if (!in_array($key, $ignored))
        {
            $packed[$key] = $value;
        }
    }
    return $packed;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文