-2

How can I convert a multidimensional array like the one below

Array(
    [0] => Array(
                    [0]=001
                    [1]=002
                    [2]=003
                )
    [1] => Array(
                    [0]=America
                    [1]=Japan
                    [2]=South Korea
                )
    [2] => Array(
                    [0]=Washington DC
                    [1]=Tokyo
                    [2]=Seoul
                )
)

into a single line array like the one below?

Array(
    [0]=001,America,Washington DC
    [1]=002,Japan,Tokyo
    [2]=003,South Korea,Seoul
)
YakovL
  • 7,557
  • 12
  • 62
  • 102
Manish
  • 3
  • 6

2 Answers2

1

Here is simple code to work around,

foreach ($text as $key => $value) {
    foreach ($value as $key1 => $value1) {
        $result[$key1][] = $value1;
    }
}
array_walk($result, function(&$item){
    $item = implode(',', $item);
});

Here is the working link

array_walk — Apply a user supplied function to every member of an array

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

The variadiac php5.6+ version: (Offers the added benefits of not breaking on missing values and inserting null where values are missing.)

Code: (Demo)

var_export(array_map(function(){return implode(',',func_get_args());},...$text));

The non-variadic version:

Code: (Demo)

foreach($text as $i=>$v){
    $result[]=implode(',',array_column($text,$i));
}
var_export($result);

Input:

$text = [
    ['001','002','003'],
    ['America','Japan','South Korea'],
    ['Washington DC','Tokyo','Seoul']
];

Output from either method:

array (
  0 => '001,America,Washington DC',
  1 => '002,Japan,Tokyo',
  2 => '003,South Korea,Seoul',
)

Nearly exact duplicate page: Combining array inside multidimensional array with same key

mickmackusa
  • 43,625
  • 12
  • 83
  • 136