PHP-通过循环用变量填充数组 [英] PHP - populate an array with variables by loop

查看:64
本文介绍了PHP-通过循环用变量填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的变量(这些变量的值)放入数组中.我有类似的变量名,所以我尝试找到一个基于循环的解决方案,该解决方案具有相同的输出:

I want to put my variables (the value of these variables) into an array. I have similar variable names, so I try to find a loop-based solution that gives the same output like that:

$str1 = "one";
$str2 = "two";
$str3 = "three";

$arr = array($str1, $str2, $str3);
foreach ($arr as $key => $value){
    echo "[", $key, "] = ", $value, "<br/>";
}

对于基于循环的解决方案,我尝试过这种方法,但不允许将值插入数组:

For the loop -based solution I tried this way but it doesn't let insert values into the array:

$str1 = "one";
$str2 = "two";
$str3 = "three";

function arrayDefine($varName, $max) {
    for ($i = 1; $i <= $max; ++$i){
        echo "$", $varName, $i;
        if ($i < $max){
            echo ", ";
        }
    }
}

$arrItems = arrayDefine(str, 3);
$arr = array($arrItems);
foreach ($arr as $key => $value){
    echo "[", $key, "] = ", $value, "<br/>";
}

第一个代码块的输出为:

The output of the first code block is:

[0] = one
[1] = two
[2] = three

但第二个显示:

$str1, $str2, $str3[0] = 

为了获得与第一个(非基于循环的)解决方案相同的结果,我应该更改/使用什么?

What should I change/use in order to get the same result as with the first (not loop-based) solution?

推荐答案

您需要了解的第一件事是将一些信息打印到输出(例如 echo )和将值分配给变量之间的区别

First thing you need to understand is the difference between printing some information to the output (eg. echo) and assigning values to variables.

您的函数仅将变量名称输出到输出中.但是,这些是字符串.程序运行后,字符串不等于一段代码.这是任何类型编程的基础知识,在完全理解变量之前,您不得尝试做任何事情.

Your function just prints variable names to the output. However, these are strings. String is not equal to a piece of code once the program is running. This is the very basics of any sort of programming, and you must not try to do anything until variables are perfectly clear to you.

现在解决.由于您的变量是全局,因此您可以通过php的 $ GLOBALS 数组访问它们.看起来像这样:

Now a solution. Since your variables are global, you can access them via php's $GLOBALS array. This would look like this:

$str1 = "a";
$str2 = "b";
$str3 = "c";

function createArray($name, $count) {
    $return_array  = array();
    for($i=0; $i<$count; $i++) {
        $return_array[$name.($i+1)] = $GLOBALS[$name.($i+1)];
    }
    return $return_array;
} 

print_r(createArray("str", 3));

通常,您在做什么是荒谬的.如果您不想存储一些数据以便可以访问所有数据,请从数组开始:

Generally, what you're doing is absurd. If you wan't to store some data so that all the data can be accessed, start with an array:

array("a", "b", "c");
or
array("str1"=>"a", ...);

使用 eval()

此外,许多初学者往往喜欢"邪恶"功能.您也可以做到. eval()字符串转换为一段代码.但是,这总是一个糟糕的解决方案,当我学习更多有关编程的知识时,我总是学到了更好的解决方案.但是,您不可能从一开始就了解所有内容,因此这是一种如何生成最危险和不安全的代码的方法:

Using eval()

Also, many beginners tend to like the "evil" function. You could do it too. eval() turns a string to a piece of code. But, it's always a bad solution and I've always learned a better one when I learned more about programming. However, you can't know everything from the beginning, so here is a way how to produce most dangerous and insecure codes:

function createArray($ name,$ count){$ return_array = array();for($ i = 0; $ i

这确实很危险,并且会引起麻烦.

function createArray($name, $count) { $return_array = array(); for($i=0; $i

This is really dangerous and will cause trouble.

我认为ManiacTwister提出的 $$ 方法是最好的.您甚至可以将复杂的字符串转换为变量:

I think that $$ approach proposed by ManiacTwister is the best. You can even turn a complicated string to a variable:

echo ${"static_text" . $string};

但是,为什么不使用数组呢?此功能应用于调试目的.

However, again, why not use arrays? This features should serve for debug purposes.

但是, 变量范围 可能会令人困惑,请参见示例:

However, the variable scopes might be confusing, see an example:

$x = 666;
function printvar($name) {
     global $$name;  //Get the variable from global scope t the function scope
     echo $$name; //if $name = "x" this evaluates into echo $x
     echo "\n";  //New line
}
printvar("x");  //Prints 666


function aFunction() {
    $x = 13;  //This $x only exists betvween {} and has nothing to do with global $x = 666
    printvar("x");  //Still prints 666!
}

这篇关于PHP-通过循环用变量填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆