PHP在函数中使用一个变量,该变量位于函数外部的数组中


PHP use a variable in a function which is in an array outside it

下面是数组($answers),您可以在最后一个数组项中看到$id:

    14 => array (
    "Joghurtos zabkása",
    "Joghurt zabbal",
    "Joghurt zabpehellyel",
    "Reggeli zabbal",
    "Egyéb <input type='"text'" name='"poll".$id."'" style='"width:100px; '" value='"'" /> "

功能内部:

function NewPoll($id,$type,$optional=false){
global $answers;
            foreach ( $answers[$id] as $key => $value ) {
                echo "
                <input type='"radio'" name='"poll".$id."'" id='"poll".$id."[".$key."]'" value='"".$key."'" />
            <label for='"poll".$id."[".$key."]'">".$value."</label><br />";
            }

我想做的是,当我从函数中打印时,通过$value变量,来自数组的$id应该是函数中的$id。$id在函数中获取值,而不是在函数外定义,但我想在加载到时使用它。我不知道我有多清楚…

您不能这样做。定义数组中的14元素时。CCD_ 2变量被替换为其值并嵌入到字符串中。一旦你开始访问后一个数组,这个特定值来自变量的字符串就没有"历史记录",现在它只是一个字符串。

例如,如果你有

$foo = 'bar';
$baz = "This string contains $foo";
echo $baz; // prints: This string contains bar
$foo = 'qux';
echo $baz; // prints: This string contains bar

在生成字符串后更改$fooNOT将该字符串内的bar更改为qux,因为bar来自变量的事实在生成字符串时丢失。

您无法执行此操作,因为您已经向字符串中注入了$id。

尝试var_dump($answers);,它不会显示您在问题中发布的输出(标识符"$id"被其内容替换)。

尝试:

class Container {
    public static $answers = array('foo', 'bar');
}

function NewPoll($id,$type,$optional=false)
{
    foreach ( Container::$answers[$id] as $key => $value )
    //...

但是,我建议更好地使用对象和类