简体   繁体   English

将相同的键组合在一个数组中并在 smarty 中打印

[英]Combining same key's in an array and print it in smarty

I have $product.features array in PrestaShop 1.7.我在 PrestaShop 1.7 中有$product.features数组。

Here is the sample data in the array.这是数组中的示例数据。 $product.features.name: $product.features.value

width: 100 m
method: Nail Down
method: Main Floor
Warranty: 25 years
Color: Red
Color: Blue

I want to print the above data as我想将上述数据打印为

Width: 100m
method: Nail Down, Main Floor
Warranty: 25 years
Color: Red, Blue

Here is the smarty code i have这是我的聪明代码

{foreach from=$product.features item=feature}
    <div class="col-md-3 col-sm-6 col-xs-12">
        <div class="name">{$feature.name}</div>
    </div>
    <div class="col-md-3 col-sm-6 col-xs-12">
        <div class="value flex_child">{$feature.value}</div>
    </div>         
 {/foreach}

Try this:尝试这个:

{foreach from=$product.features item=feature}
    <div class="col-xs-12">
        <div class="name">{$feature.name}: {$feature.value}</div>
    </div>         
{/foreach}

One option is to prepare the features array for looping the keys and values.一种选择是准备特征数组以循环键和值。

For example, using array_reduce and explode to return an array where the keys are the part before the : and the values are the imploded result with , as the delimiter:例如,使用array_reduceexplode返回一个数组,其中键是:之前的部分,值是 imploded 结果,其中,作为分隔符:

$features = [
    "width with: 100 m",
    "method: Nail Down",
    "method: Main Floor",
    "Warranty: 25 years",
    "Color: Red",
    "Color: Blue"
];

$features = array_reduce($features, function($carry, $item){
    $parts = explode(":", $item);
    $carry[$parts[0]][] = $parts[1];
    return $carry;
});

foreach ($features as $key => $value) {
    echo "$key: " . implode(',', $value) . PHP_EOL;
}

Output Output

width:  100 m
method:  Nail Down, Main Floor
Warranty:  25 years
Color:  Red, Blue

See a Php demo查看Php 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM