-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
)
3
  • 1
    Lazy person's solution: array_map(function ($v) { return implode(",",$v); }, $array); Commented Sep 7, 2017 at 9:34
  • see implode() to convert into strings 2nd level arrays. Commented Sep 7, 2017 at 9:34
  • It was easy for coding too and it helps me a lot thanks man. Commented Sep 8, 2017 at 3:35

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.