简体   繁体   中英

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

I have $product array. 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']

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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