的一部分,我試圖做財產以後這樣的一個變量:訪問使用計數器作爲變量名
$cat1 = array('hello', 'everyone');
$cat = array('bye', 'everyone');
for($index = 0; $index < 2; $index++) {
echo $cat$index[1];
}
這並不當然工作。 我需要在這裏更改什麼?
的一部分,我試圖做財產以後這樣的一個變量:訪問使用計數器作爲變量名
$cat1 = array('hello', 'everyone');
$cat = array('bye', 'everyone');
for($index = 0; $index < 2; $index++) {
echo $cat$index[1];
}
這並不當然工作。 我需要在這裏更改什麼?
你應該使用嵌套數組,但是這可以完成。
$cat1 = array('hello', 'everyone');
$cat2 = array('bye', 'everyone');
for($i = 1; $i <= 2; $i++) {
echo ${'cat' . $i}[1];
}
參考:http://php.net/language.variables.variable
這將是雖然好得多:
$cats = array(
array('hello', 'everyone'),
array('bye', 'everyone')
);
foreach ($cats as $cat) {
echo $cat[1];
}
這是你的意圖嗎?
$cat0 = array('hello', 'everyone');
$cat1 = array('bye', 'everyone');
for($index = 0; $index < 2; $index++) {
$varname = 'cat'.$index;
echo $varname[0].' '.$varname[1];
}
爲了呼應元素中數組,你需要使用
echo $cat[$index]
你的榜樣。我不確定$index[1]
應該做什麼?也許我誤解了你的問題。
不能引用$指數這樣的,它不是一個數組。
echo $cat[$index];
是你想要做的。
如果堅持做這種方式 ...
echo ${'cat' . $index}[1];
你爲什麼不使用嵌套的數組? – 2010-12-01 17:40:51
請回到您的問題並標出最佳答案。 – Jonah 2010-12-01 17:54:37