PHP:使用动态变量创建for循环

I'm trying to slim down the code:

I want to make a for loop out of this part, but it wouldn't work.

$line1 = $frage1[0] . '|' . $frage1[1] . '|' . $frage1[2] . '|' . $frage1[3];
$line2 = $frage2[0] . '|' . $frage2[1] . '|' . $frage2[2] . '|' . $frage2[3];
$line3 = $frage3[0] . '|' . $frage3[1] . '|' . $frage3[2] . '|' . $frage3[3];
$line4 = $frage4[0] . '|' . $frage4[1] . '|' . $frage4[2] . '|' . $frage4[3];
$line5 = $frage5[0] . '|' . $frage5[1] . '|' . $frage5[2] . '|' . $frage5[3];

This is my attempt:

for ($i=1; $i<6; $i++){
        ${line.$i} = ${frage.$i}[0] . '|' . ${frage.$i}[1] . '|' . ${frage.$i}[2] . '|' . ${frage.$i}[3];
    }

EDIT: This is the solution that works (just so simple :-p):

for ($i=1; $i<18; $i++){
        ${"line".$i} = implode("|", ${"frage".$i});
        fwrite($antworten, ${"line".$i});
    }
for ($i=1; $i<6; $i++){
        $line[$i] = $frage[0] . '|' . $frage[1] . '|' . $frage$i[2] . '|' . $frage$i[3];
    }

This will insert the same thing you posted abov e in line 1 to 6. Is this what you are looking for?!

for ($i=1; $i<6; $i++){
    ${"line$i"} = ${"frage$i"}[0] . '|' . ${"frage$i"}[1] . '|' . ${"frage$i"}[2] . '|' . ${"frage$i"}[3];
}

That works too!

TL;DR

You might find the documentation on variable variables useful but it looks like the problem is that PHP cannot handle the unquoted string inside your curly brackets.

So instead of ${frage.$i} you need ${"frage$i"}.

Another Approach

However, this is probably not the clearest way to solve this problem. It certainly gives me a bit of a headache trying to work out what this code is trying to do. Instead I would recommend adding all of your $frage to an array first and then looping as follows:

$lines = array();
$frages = array($frage1, $frage2, $frage3, $frage4, $frage5)

foreach($frages as $frage) {
  $lines[] = join('|', $frage);
}

Note in particular that you can use join to concatenate each $frage with a | inbetween each, rather than doing this concatenation manually. You could always use [array_slice][2] if you really did only want the first 4 elements of the array to be joined.

If you have a significant number of $frage variables and don't want to add them to an array manually then:

$frages = array();

for($i = 1; $i < x; $i++) {
  $frages[] = ${"frage$i"}
}

If you really need each $line variable rather than an array of lines, then you can use extract although this will give you variables like $line_1 rather than $line1:

extract($lines, EXTR_PREFIX_ALL, "line")

However, I would recommend taking a serious look at why you have these numbered $frage being generated and why you need these numbered $line as your output. I would be very surprised if your code could not be re-factored to just use arrays instead, which would make your code much simpler, less surprising and easier to maintain.