使用计数器作为变量名称的一部分访问变量 [英] Access a variable using a counter as part of the variable name
本文介绍了使用计数器作为变量名称的一部分访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图做这样的事情:
$cat1 = array('hello', 'everyone');
$cat = array('bye', 'everyone');
for($index = 0; $index < 2; $index++) {
echo $cat$index[1];
}
当然不行.我需要在这里更改什么?
It doesn't work of course. What do I need to change here?
推荐答案
您应该使用嵌套数组,但这可以做到.
You should use nested arrays, but this can be done.
$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];
}
这篇关于使用计数器作为变量名称的一部分访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文