如何在foreach中将字符串合并为单个字符串?的PHP

时间:2018-07-22 07:27:57

标签: php string foreach

我有以下foreach代码:

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';

}

输出为:

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,"

对于CSV,所有路径都必须以逗号分隔,如下所示:

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

这是我的CSV数组的输出:

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

)`

仅将最后一个值写入数组 https://path.to/the/picture_5.jpg

我尝试使用以下示例:How to combine strings inside foreach into single string PHP

但没有成功,我希望有人能帮助我

预先感谢您的帮助

最好的问候 达什米尔

1 个答案:

答案 0 :(得分:0)

假设您希望所有图像都使用“,”分隔符进行串联,则可以继续使用$whole_pic_url串联到.=

只需声明变量并以空字符串开始即可。 $whole_pic_url = ""

然后在循环中执行: $whole_pic_url .= "https://www.path.to".$PIC_url . ',';

整个代码应如下所示:

$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';

}

您可以将所有图像全部分组为一个数组,然后将其内嵌为字符串。

$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);