Semicolon
Semicolon

Reputation: 1935

How to merge values of array into comma seperated string of similar keys of array

I have this array.

$test['color'][0] = "red";
$test['color'][1] = "blue";
$test['color'][2] = "black";
$test['plug'][3] = "US";
$test['plug'][4] = "UK";

i am trying to achieve this from above array.

$test2['color'] = "red,blue,black"; 
$test2['plug'] = "US,UK";

What would be the best logic to implement this.

Upvotes: 0

Views: 2562

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

Call implode() on each row and use a comma as the glue character. array_map() is a concise way to iterate the rows.

Code: (Demo)

var_export(
    array_map(fn($row) => implode(',', $row), $test)
);

Output:

array (
  'color' => 'red,blue,black',
  'plug' => 'US,UK',
)

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33512

You can use a little logic and a few PHP functions quite nicely:

<?php

    $array['color'][0] = "red";
    $array['color'][1] = "blue";
    $array['color'][2] = "black";
    $array['plug'][3] = "US";
    $array['plug'][4] = "UK";
    $test2=array();
    foreach($array as $key=>$val)
    {
        $test2[$key]=implode(',',$val);
    }

    print_r($test2);
?>

Output:

Array
(
    [color] => red,blue,black
    [plug] => US,UK
)

Edit: First answer was wrong and overly complicated. This is a one control structure solution.

Upvotes: 2

marekful
marekful

Reputation: 15351

$test2['color'] = implode(',', $test['color']);
$test2['plug'] = implode(',', $test['plug']);

print_r($test2);

Upvotes: 0

Related Questions