在数组中组合相同的键并在 php 中打印



我有$product数组。这是数组中的示例数据。

[feature]=>[value]
[width]=> [100 m]
[method]=> [Nail Down]
[method]=> [Main Floor]
[Warranty]=> [25 years]
[Color]=> [Red]
[Color]=> [Blue]

我想将以上数据打印为

Width: 100m
method: Nail Down, Main Floor
Warranty: 25 years
Color: Red, Blue
Here is the smarty code i have

我有以下代码。

foreach($product as $key=$Value){
echo $key."=".$value.<br>;
} 

请注意,我不想生成另一个数组然后打印。提前感谢

在数组中不能有两个值具有与示例中相同的键。你的意思是这个值是一个数组吗?如$product['method'] = ['Nail Down', 'Main Floor']

如果是这样,您可以使用以下代码:

echo $key."=" . (is_array($value) ? join(', ', $value) : $value) ."<br>";

在PHP中不能有多个值不同的键。这意味着在示例数组中不能有这样的数据。这将变成:

[feature]=>[value]
[width]=> [100 m]
[method]=> [Main Floor]
[Warranty]=> [25 years]
[Color]=> [Blue]

这就是你永远无法实现目标的原因。您应该为数组中的变体提供不同的键。

最新更新