如何使用与$ variable name分配给数组的键名相同的数组?

时间:2017-04-14 10:14:17

标签: php arrays multidimensional-array

我正在使用$ variables(具有不同的名称)分配一个数组,其中包含一些值,如:

array($one, $two, $three);

现在我正在搜索一种方式,有任何方法可以直接分配上面的数组,其键名与变量名相同,最后我想使这个数组像:

array(
      "one" => $one, 
      "two" => $two, 
      "three" => $three
)

如果在使用变量分配数组时可以做到这一点那么我会对我有好处然后我可以轻松地提取()这个数组而且我不必执行操作来打开这个数组并分配这些值$ variable name,如果有任何function(),那么它会很好,如果有人知道

请求帮助

2 个答案:

答案 0 :(得分:0)

以下是您添加2次get_defined_vars();

的限制

PHP code demo

<?php

$someVariable=1;
$someVariable=2;
$someVariable=3;
$definedOld=get_defined_vars();//this will bring all variables defined till now.

$one="test1";
$two="test2";
$three="test3";

$definedNew = get_defined_vars();//this will bring all variables defined till now.

$variables=array_diff($definedNew,$definedOld);//finding the difference
print_r($variables);

答案 1 :(得分:0)

compactextract的倒数。像这样使用它:

$array = compact ('one', 'two', 'three');

这将查找名为“one”,“two”,“three”的变量,并且完全符合您的要求。

相关问题