解析一个包含商品变体信息的字符串,并将其转换为结构化的数组格式。

parse_variations 函数接收一个字符串 $variations_str,该字符串包含多个商品变体的信息,每个变体由 ||| 分隔。每个变体的信息又由 @@@ 分隔成多个部分,包括属性、价格、库存、SKU、图片等。

<?php
$variations_str = "颜色::红色###尺寸::L@@@222@@@111@@@1000@@@SKU001@@@11@@@https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/doubao/desktop_online_web/static/image/assistant-img-01.0af0a1ed.png###https://woo.alidhgate.com/wp-content/uploads/2025/06/683e5469e03c5_1-150x150.jpg|||颜色::红色2###尺寸::L2@@@222@@@111@@@1000@@@SKU001@@@11@@@https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/doubao/desktop_online_web/static/image/assistant-img-01.0af0a1ed.png###https://woo.alidhgate.com/wp-content/uploads/2025/06/683e5469e03c5_1-150x15022.jpg@@@downurl";
function parse_variations($variations_str) {
$current = [];
$variations=[];
foreach (explode('|||',$variations_str) as $attributeses){

$attributes = explode('@@@',$attributeses);
$attributes0 = explode('###',$attributes[0]);
foreach ($attributes0 as $atts){
@list ($name,$val) = explode('::',$atts);
$current[$name]=$val;
}

$variations[] = [
'attributes' => $current,
'regular_price' => $attributes[1] ?? '', // 原价
'sale_price' => $attributes[2] ?? '', // 促销价
'stock' => $attributes[3] ?? '', // 库存
'sku' => $attributes[4] ?? '', // SKU
'weight' => $attributes[5] ?? '', // 重量
'images' => isset($attributes[6]) ? explode('###', $attributes[6]) : [], // 图片
'download_url' => $attributes[7] ?? '' // 下载地址
];

}
return [$variations];

};

$result = parse_variations($variations_str);
print_r($result);

解析后输出

Array
(
[0] => Array
(
[0] => Array
(
[attributes] => Array
(
[颜色] => 红色
[尺寸] => L
)

[regular_price] => 222
[sale_price] => 111
[stock] => 1000
[sku] => SKU001
[weight] => 11
[images] => Array
(
[0] => https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/doubao/desktop_online_web/static/image/assistant-img-01.0af0a1ed.png
[1] => https://woo.alidhgate.com/wp-content/uploads/2025/06/683e5469e03c5_1-150x150.jpg
)

[download_url] =>
)

[1] => Array
(
[attributes] => Array
(
[颜色] => 红色2
[尺寸] => L2
)

[regular_price] => 222
[sale_price] => 111
[stock] => 1000
[sku] => SKU001
[weight] => 11
[images] => Array
(
[0] => https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/doubao/desktop_online_web/static/image/assistant-img-01.0af0a1ed.png
[1] => https://woo.alidhgate.com/wp-content/uploads/2025/06/683e5469e03c5_1-150x15022.jpg
)

[download_url] => downurl
)

)

)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。