在foreach循环中动态创建PHP变量

时间:2018-09-18 06:18:39

标签: php loops foreach

我只是试图动态创建PHP变量。下面是我尝试过的代码。

    if($BrickTerritorys)
    {
            foreach($BrickTerritorys as $index=>$BrickTerritory)
            {
                ${"$T.$index"}= $BrickTerritory->TerritoryID;
                ${"'Weightage'.$index"} = $BrickTerritory->Weightage;
            }
            echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
    }

while 
$BrickTerritorys is 
 [1] => stdClass Object
        (
            [id] => 119
            [TerritoryID] => HYD-2-CMD
            [BrickCode] => 16
            [BrickName] => BUHURO
            [Weightage] => 40.00
            [BPCode] => bp00066
            [GroupCode] => CMD
        )
    [2] => stdClass Object
        (
            [id] => 36330
            [TerritoryID] => HYD-1-CMD
            [BrickCode] => 16
            [BrickName] => BUHURO
            [Weightage] => 60.00
            [BPCode] => bp00066
            [GroupCode] => CMD
        )

最后一次打印时,什么也没打印。请提供任何帮助。

预先感谢

3 个答案:

答案 0 :(得分:1)

尝试像这样更改这些行:

        ${"T$index"}= $BrickTerritory->TerritoryID;
        ${"Weightage$index"} = $BrickTerritory->Weightage;

在您的代码${"$T.$index"}中,$ T正在搜索变量,并且应该获得未定义的变量$ T,因此,如果要具有T1,T2变量,则必须删除$符号。

之后,${"'Weightage'.$index"},Weightage之间的撇号意味着您的变量将看起来像'Weightage'.1,'Weightage'.2 ..等。

答案 1 :(得分:1)

${"T$index"}${"Weightage$index"}

您不需要点,也可以使用${'T' . $index}。看点。它不是在“”中的加法运算。遵循以下代码:

if($BrickTerritorys)
{
    foreach($BrickTerritorys as $index=>$BrickTerritory)
    {
        ${"$T.$index"}= $BrickTerritory->TerritoryID;
        ${"'Weightage'.$index"} = $BrickTerritory->Weightage;
    }
    echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}

答案 2 :(得分:1)

这可以通过几种不同的方法来完成,而无需使用可变变量并产生完全动态的结果。

这里是一个:(Demo

$array = (array)$BrickTerritorys;             // cast as array
$tids = array_column($array, 'TerritoryID');  // isolate column data
$was = array_column($array, 'Weightage');     // isolate column data
$merged = array_merge($tids, $was);           // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
    echo str_repeat('-', $i) , $v;            // increase hyphens on each iteration starting from 0
}

输出:(注意,没有硬编码的回声)

HYD-2-CMD-HYD-1-CMD--40.00---60.00