我正在使用数组来存储在其他地方动态生成的其他数组的名称。我需要遍历“names”数组并访问“named”数组的内容。像这样:
$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");
foreach ($process_array in $names) {
// how to access the contents of $one, $two and $three using only $names??
}
我确信我应该能够以某种方式利用变量变量,但我读过的所有例子都显示了我正在尝试做的逻辑逆转(除非我误解了基本原理 - 完全可能!)
非常感谢任何建议。
答案 0 :(得分:3)
$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");
foreach ($names as $name) {
// how to access the contents of $one, $two and $three using only $names??
print_r(${$name});
}
答案 1 :(得分:2)
PHP有一个名为variable variables的功能:
foreach ($names as $name) {
$$name;
}
对于只是变量,您可以使用上面的语法($$name
)。如果要使用表达式命名变量,请使用括号语法,如${"foo".$name}
。
答案 2 :(得分:1)
喜欢这个吗?
foreach ($names as $name) {
var_dump($$name); // do something else
}
答案 3 :(得分:0)
$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");
foreach ($names as $name) {
foreach ($$name as $value) {
// $value contains the array values.
}
}
要注意它是foreach ($array as $value)
,而不是foreach ($value in $array)
。