2016-10-21 10 views
1

配列から読み込む関数をPHPで作成しようとしています。配列の値を読み込むために、テキストと配列のID番号を連結しようとしていますが、配列の値ではなく連結されたテキストが返されます。ここでphpの配列項目にアクセスするためにテキスト値を連結する

は私のコードです:

//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: Variable VariablesPHP: Variable Parsingを参照)変数にあなたがしようとしている何をすべきか、このように参照する必要

+1

$ converted_word = $ {$ word_to_convert} [2];しかし、あなたがやっていることをやるより良い方法があります。 – AbraCadaver

答えて

0

$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を使用して、その配列から単語を使用しています。

+0

ありがとうございました。中かっこが働き、余分なアンダースコアを見つけてくれてありがとう。期待どおりに働く。私はちょうどphpを学んでいて、関数について演奏しています。私は多次元配列をテストします。 –

+0

NP。変数名を動的に作成またはアクセスしようとしている場合は、配列を使用する必要があります。 – AbraCadaver

関連する問題