连接文本值以访问php中的数组项

时间:2016-10-21 20:11:06

标签: php

我试图在php中创建一个从数组中读取的函数。我试图连接文本和数组ID号,以读取数组中的值,但它是返回的连接文本,而不是数组的值。

这是我的代码:

//arrays with words in dictionary

$dictionary_word1 = array("test1","test2","test3");

$dictionary_word2 = array("test4","test5","test6");

$dictionary_word3 = array("test7","test8","test9");


$word_to_lookup = "dictionary_word_1"; 
//value to send to function

$returned_word = convert_word($word_to_lookup); 
//value returned from function

echo "<br>the returned word from the function is " . $returned_word; 
//the text "$dictionary_word_1[2]" is displayed instead of array value

echo "<br>the value in the array is " . $dictionary_word1[2];  
//this displays correcty as "test3"

function convert_word($word_to_convert)
{
    global $dictionary_word1;   
    $converted_word = '$'.$word_to_convert .'[2]';  
    return $converted_word;
}   

有人能给我任何关于我哪里出错的提示吗?

1 个答案:

答案 0 :(得分:0)

您需要以这种方式引用变量来执行您尝试的操作(请参阅PHP: Variable VariablesPHP: Variable Parsing):

$converted_word = ${$word_to_convert}[2];

但是,请注意dictionary_word_1$dictionary_word1之间的区别?不行。

无论如何,只要你这样做,你就会更好地使用数组。在这种情况下是一个多维数组。考虑:

$words[1] = array("test1","test2","test3");
$words[2] = array("test4","test5","test6");
$words[3] = array("test7","test8","test9");

然后你总是使用$words只更改索引,然后使用该数组中的单词。