Php 反向变量?
我使用一个数组来存储在别处动态生成的其他数组的名称。我需要遍历“names”数组并访问“named”数组的内容。大概是这样的:Php 反向变量?,php,dynamic,arrays,variables,Php,Dynamic,Arrays,Variables,我使用一个数组来存储在别处动态生成的其他数组的名称。我需要遍历“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
$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??
}
我确信我应该能够以某种方式利用变量,但我读过的所有例子都显示了我试图做的事情的逻辑相反(除非我误解了基本原则——完全可能!)
非常感谢您提供的所有建议。PHP有一个名为:
$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});
}
对于变量,您可以使用上面的语法($$name
)。当您想使用表达式来命名变量时,请使用括号语法,如${“foo”。$name}
PHP有一个名为:
对于变量,您可以使用上面的语法($$name
)。当您想使用表达式来命名变量时,请使用括号语法,如${“foo”。$name}
这样
foreach ($names as $name) {
var_dump($$name); // do something else
}
像这样
foreach ($names as $name) {
var_dump($$name); // do something else
}
注意它是foreach($array as$value)
,而不是foreach($array中的value)
注意它是
foreach($array as$value)
,而不是foreach($array中的value)
是的,您误解了变量。它们正是你想要的。是的,你误解了变量。他们做的正是你想要的。看起来我想的太多了,答案就在我面前。所有答案都正确,谢谢大家!看起来我想的太多了,答案就在我面前。所有答案都正确,谢谢大家!
$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.
}
}