数组名中的花括号变量,PHP

数组名中的花括号变量,PHP,php,arrays,variable-variables,Php,Arrays,Variable Variables,我知道这里有很多类似的问题,我想我都读过了。我的问题是,我试图在数组列表中循环,并从每个数组中获取一个值。阵列是由第三方设置的,我无权配置接收阵列的方式。以下是我目前掌握的情况: for ($i = 0; $i < $length; $i++) { // Both of these work and return the value I need echo $post->related_credits_0_related_show[0]; echo "{$

我知道这里有很多类似的问题,我想我都读过了。我的问题是,我试图在数组列表中循环,并从每个数组中获取一个值。阵列是由第三方设置的,我无权配置接收阵列的方式。以下是我目前掌握的情况:

for ($i = 0; $i < $length; $i++) {

    // Both of these work and return the value I need
    echo $post->related_credits_0_related_show[0]; 
    echo "{$post->related_credits_0_related_show[0]}"

    // But none of these do, and I need to loop through a handful of arrays
    echo "{$post->related_credits_{$i}_related_show[0]}";
    echo "{$post->related_credits_${i}_related_show[0]}";
    echo "{$post->related_credits_{${i}}_related_show[0]}";
    echo "{$post->related_credits_".$i."_related_show[0]}";

}
($i=0;$i<$length;$i++)的
{
//这两种方法都可以工作并返回所需的值
echo$post->related_credits_0_related_show[0];
回显“{$post->related_credits_0_related_show[0]}”
//但这些都不行,我需要遍历一些数组
回显“{$post->related_credits{$i}{$i}{u related_show[0]}”;
回显“{$post->related_credits{i}{u related_show[0]}”;
回显“{$post->related_credits{${i}}{u related_show[0]}”;
回显“{$post->related_credits...$i.”_related_show[0]}”;
}
我已经尝试了很多(很多!)更多的组合,我不会包括在内。我还尝试将$I转换为字符串。有一段时间我一直在用头撞这个

提前感谢您的帮助。

您可以使用:

$varname = "related_credits_$i_related_show";
$array =  $post->$varname;
echo $array[0]; 
较短的形式是:

$post->{"related_credits_{$i}_related_show"}[0];

在这里您可以找到所谓的“变量”:

您需要在这里使用变量。基本用法如下:

$var = 'Hello there!';
$foo = 'var';
echo $$foo;
     ^^--- note the double $-sign
这将输出:

Hello there!
除了
$$foo
,您还可以编写以下内容:

echo ${"$foo"};
for ($i=0; $i < $length; $i++) { 
    $post->{"related_credits_{$i}_related_show"}[0];
}
如果变量名更复杂,还可以执行以下操作:

echo ${"some_stuff_{$foo}_more_stuff"};
在本例中,表示变量名的字符串包含一个变量,该变量也被包装在大括号中(
{}
)。这样做是为了避免常数、数组索引等方面的问题。但是如果您的用例不涉及这些问题,您就不必担心了

对于您的特定问题,您可以使用以下方法:

echo ${"$foo"};
for ($i=0; $i < $length; $i++) { 
    $post->{"related_credits_{$i}_related_show"}[0];
}
for($i=0;$i<$length;$i++){
$post->{“相关的{$i}相关的}[0];
}
或者,如果您更喜欢串联:

for ($i=0; $i < $length; $i++) { 
    $res = $post->{'related_credits_'.$i.'_related_show'}[0];
}
for($i=0;$i<$length;$i++){
$res=$post->{'related_credits'.$i.'u related_show'}[0];
}

请参阅。

您的示例没有问题,但有一个轻微的错误-即,计算将发生在
$i_related_show
而不是
$i
,错误是存在未定义的变量
$i_related_show
”。然而,+1是一个很好的例子。@N.B.:啊,对。我在发布之前没有测试过这个。现在修复:)我发现被黑客攻击的文件包含$xyz{26}等,可以解释吗?这几乎是通过一次编辑完成的,我必须在$I周围放上花括号。Stackoverflow会让我在3分钟内接受答案,谢谢你这么快!是 啊我还添加了一个缩短的备选方案。