-1

i have this foreach code:

if(property_exists($product, "images")){

    foreach($product->images as $images){


        $PIC_url = $images->original_url;



            $whole_pic_url = "https://www.path.to".$PIC_url . ',';

            echo "<pre>";
                var_dump ($whole_pic_url);
            echo "</pre>";
    }
} else {

    $whole_pic_url = 'https://path.to/alternative/picture.jpg';

}

the output is:

string(54) "https://path.to/the/picture_1.jpg,"
string(68) "https://path.to/the/picture_2.jpg,"
string(69) "https://path.to/the/picture_3.jpg,"
string(69) "https://path.to/the/picture_4.jpg,"
string(73) "https://path.to/the/picture_5.jpg,"

For the CSV all paths must be a row separated by commas like this:

https://path.to/the/picture_1.jpg,https://path.to/the/picture_2.jpg,ect.

this is the output of the array for my CSV:

`Array([0] => 1;Article_Name;path/to/the/article;category;price;ID;5;description;available ;https://path.to/the/picture_5.jpg,;2

)`

Only the last value is written to the array https://path.to/the/picture_5.jpg,

i have tried with this examples: How to combine strings inside foreach into single string PHP

but without success, i hope somebody can help me

thank you in advance for your help

best regards dashmir

  • Don't use var_dump. Use echo and build the string you need – Andreas Jul 22 '18 at 07:34
  • Hello Andreas, inside my if (foreach), i can see with echo the paths in a row,that is what i want but outside the if (foreach) its still written the last value in the CSV Array. – Dashmir Kasa Jul 22 '18 at 08:19

1 Answers1

0

Assuming you want all images to be concatenated with a "," separator, you can just keep concatenating to $whole_pic_url using .=

Just declare the variable and initiate with an empty string. $whole_pic_url = ""

Then in your loop do: $whole_pic_url .= "https://www.path.to".$PIC_url . ',';

The entire code should look like:

$whole_pic_url = "";
if(property_exists($product, "images")){

    foreach($product->images as $images){


        $PIC_url = $images->original_url;



            $whole_pic_url .= "https://www.path.to".$PIC_url . ',';

            echo "<pre>";
                var_dump ($whole_pic_url);
            echo "</pre>";
    }
} 
else {
    $whole_pic_url .= 'https://path.to/alternative/picture.jpg';

}

You can all group all the images into an array, then implode the array to be a string.

$images_array = [];
if(property_exists($product, "images")){

    foreach($product->images as $images){


        $PIC_url = $images->original_url;
            $images_array[] = "https://www.path.to".$PIC_url . ',';

            echo "<pre>";
                var_dump ($whole_pic_url);
            echo "</pre>";
    }
} 
else {
    $images_array[] = 'https://path.to/alternative/picture.jpg';

}
$whole_pic_url = implode(",", $images_array);
Amin
  • 663
  • 1
  • 8
  • 25