首页 > 解决方案 > PHP - 输出包含特定文本标记的数组值

问题描述

我正在使用一个函数将 Shopify 中的产品集合输出到 WordPress 页面上。

除了在 Shopify 中作为标签输入的自定义值外,我的大部分数据都正确显示。使用 api,然后我尝试在每个产品自定义值/文本之前获取格式为 att:Subtitle: 的产品副标题的特定标签。

这是我必须得到的代码(我在中间评论了其他不成功的尝试) - 这是在整个代码中显示 Shopify 集合中的 4 种产品:

 // Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Evaluate if there is a string with att:Subtitle in the product tags
// https://tecadmin.net/check-string-contains-substring-in-php/
$subtitle_attribute_key = "att:Subtitle:";

if (strpos($tags, 'att:Subtitle:') !== false) {  
    // Returns a numbered value corresponding to my subtitle attribute
    // $key = array_search($subtitle_attribute_key, $product_tags);
    $sub = strpos($tags, $subtitle_attribute_key);

    // Turns the numbered value into a text value
    // $numArray = explode(" ", $sub);
    // var_dump($numArray);
    $value = print_r($sub, true);
    // $value = array_search("att:Subtitle:",$product_tabs);
    // $value = array_search("att:Subtitle:", $tabs); // Warning: array_search() expects parameter 2 to be array, null given
    // $result = $product_tags['$value']; // my attempt to return the text

    // Remove att:Subtittle: in front of the subtitle value to output the clean final value
    $subtitle = ltrim($value, 'att:Subtitle:');
}

到目前为止,它作为一个数字值出现,我正在显示 $subtitle... 但我无法弄清楚如何显示自定义文本值。

有任何想法吗?

谢谢

编辑:我正在使用具有多个标签的产品,我无法控制这些。在标签中,我试图找到以 att:Subtitle: 开头的标签,但仅在该标记之后显示自定义值。

当我回显 $tags 时,ist 会出现如下内容:

att:Benefit:balance, att:Perfect:Combination Skin, att:Size: 1.8 oz, att:Subtitle: Multi-Tasking Product, Key Ingredient 1, Key Ingredient 2, Essentials, meta-related-product-xyz, meta-related-product-brandname

他们都有不同的标签列表

标签: phparrayswordpressstringshopify

解决方案


因此,据我所知,您正试图从产品描述的标签中删除“att:Subtitle:”?也许您应该尝试在标签数组上替换该值

// Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Get rid of attribute on product tag
for($i = 0; $i < count($product_tags); $i++){
    $subtitle = str_replace(':att:Subtitle','',$product_tags[i]);
}

推荐阅读