如何使用某些值递增变量并重新排列结果

时间:2018-10-07 07:26:20

标签: php increment

我想使用以下值递增此变量:

$Variable = "AAAA1 VALUE1; \
             BBBB1 VALUE1; \
             CCCC1 VALUE1";

因此,我编写了以下简单代码:

for($i=1; $i<3; $i++) {
$Variable = "AAAA$i VALUE$i; \
             BBBB$i VALUE$i; \
             CCCC$i VALUE$i";
}

我得到了这2个输出结果:

  

AAAA1 VALUE1
BBBB1 VALUE1
CCCC1 VALUE1

AAAA2 VALUE2
BBBB2 VALUE2
CCCC2 VALUE2

但是我想要的是得到一个这样的完整结果:

  

AAAA1 VALUE1
AAAA2 VALUE2

BBBB1 VALUE1
BBBB2 VALUE2

CCCC1 VALUE1
CCCC2 VALUE2

2 个答案:

答案 0 :(得分:3)

打击代码:

"AAAA$i VALUE$i;  
 BBBB$i VALUE$i;  
 CCCC$i VALUE$i";

您要在每一行中进行迭代!

$variable = explode("\n",$Variable);

现在$variable是可迭代的,或使用数组:

$variable=[
             "AAAA%input1% VALUE%input1%;",
             "BBBB%input1% VALUE%input1%;",
             "CCCC%input1% VALUE%input1%;",
];

$final_string="";
foreach($variable as $var){

    for($i=1; $i<3; $i++) {
        $final_string. = str_replace("%input1%",$i,$var) ."\n";
    }

}

echo $final_string;

答案 1 :(得分:2)

您可以使字符串成为数组,并逐个循环每个项目,并在与您类似的for循环内构建字符串。

$Variable = "AAAA VALUE
BBBB VALUE
CCCC VALUE";
$startval = 1;
$endval = 5;

$var = explode("\n", $Variable);

$str = "";
foreach($var as $v){
    $temp = explode(" " , $v);
    //Loop from startval to endval and build your string
    for($i=$startval; $i<=$endval; $i++){
        $str .= $temp[0] .$i . " " . $temp[1] .$i. "\n";
    }
    $str .= "\n"; // add new line
}

echo $str;

输出:

AAAA1 VALUE1
AAAA2 VALUE2
AAAA3 VALUE3
AAAA4 VALUE4
AAAA5 VALUE5

BBBB1 VALUE1
BBBB2 VALUE2
BBBB3 VALUE3
BBBB4 VALUE4
BBBB5 VALUE5

CCCC1 VALUE1
CCCC2 VALUE2
CCCC3 VALUE3
CCCC4 VALUE4
CCCC5 VALUE5

https://3v4l.org/OPA8K