简体   繁体   English

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

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

I have $product array.我有 $product 数组。 Here is the sample data in the array.这是数组中的示例数据。

[feature]=>[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

I have the following code.我有以下代码。

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

Please note that i don't want to generate another array and then print.请注意,我不想生成另一个数组然后打印。 Thanks in advance提前致谢

You can't have two values with the same key in array as in your example.数组中不能有两个值与示例中的键相同。 Did you mean the value is an array?你的意思是这个值是一个数组吗? Such as $product['method'] = ['Nail Down', 'Main Floor']$product['method'] = ['Nail Down', 'Main Floor']

If so you can use the following code:如果是这样,您可以使用以下代码:

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

You can't have multiple keys with differnet values in PHP. PHP 中不能有多个具有不同值的键。 This means that you can't have such data in the sample array.这意味着您不能在示例数组中包含此类数据。 That would become:那将变成:

[feature]=>[value]

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

That's why you'll never achieve the goal.这就是为什么你永远无法实现目标。 You should provide different keys for variations in your array.您应该为数组中的变化提供不同的键。

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

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