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


concatenate text values to access array item in 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;
}   

谁能给我任何提示,我在哪里做错了?

您需要以这种方式引用变量来执行您正在尝试的操作(参见PHP:变量变量和PHP:变量解析):

$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只是改变索引然后从数组中使用一个词