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

时间:2022-09-13 13:22:06

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

PHP有一个函数提取,它将像这样转换一个数组:

$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?

在PHP中有这样的东西吗?

4 个解决方案

#1


16  

You can use compact() to achieve this.

您可以使用compact()来实现此目的。

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

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

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

#2


3  

like this

喜欢这个

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

#3


1  

$array = get_defined_vars()

See get_defined_vars()

请参阅get_defined_vars()

#4


1  

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;
}

#1


16  

You can use compact() to achieve this.

您可以使用compact()来实现此目的。

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

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

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

#2


3  

like this

喜欢这个

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

#3


1  

$array = get_defined_vars()

See get_defined_vars()

请参阅get_defined_vars()

#4


1  

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;
}