teckfolls teckfolls - 1 month ago 20
PHP Question

PHP foreach Loop (imagepng) Position dual

I dont get it, realy...
I'm creating a Image with:

header('Content-type: image/png');
imagepng($image);


And need to use foreach.
I hope you know what "imagettftext" is.

Here is my Code:



$position_text_array = array(26,44,62,80,98,116,134,152,170,188,206,224,242,260,278,296);
$position_text_array2 = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

foreach ($position_text_array2 as $index => $value) {
foreach ($position_text_array as $index_p => $value_p) {
imagettftext($image, 10, 0, $position_text_width, $value_p, $color_item0, $font, $value);
}
}





On my Code the Output will be on EVERY OUTPUT Line every $position_text_array2 number.

Screenshot: http://puu.sh/s3Z0X/9257124277.png

$position_text_array = Y Position
(Up, Down).

$position_text_array2 = Thats what I want to output
.

-

But if I change

$color_item0, $font, $value);


to

$color_item0, $font, $value_p);


The Output will be on every line, the Y Kordination (only 1 Number)

Screenshot: http://puu.sh/s40tC/06b7ba026c.png

Sorry for my bad english and bad explain.
I hope you understand it what I mean.

What I do wrong?

Answer

You're nesting two loops. Since both arrays have 16 elements, you're executing your text drawing call 16*16 = 256 times. That means you're DRAWING OVER each line of text 16 times, with different values.

You should have only a SINGLE loop, and use the index from that loop to refer to the other array.

foreach($position_text_array as $index => $text_to_draw) {
    $y_pos = $position_text_array[$index];
    imagettftext($image, 10, 0, $x_pos, $y_pos, $color_item0, $font, $text_to_draw);
}