'Transpose multidimensional array and join values with commas

How to group by comma of every value as per same key? I need to re-orientate the array so that rows become columns and the new rows need to be joined together with commas to form strings.

My input:

[
    [201767.11, 514324.91, 73205.74],
    [349399.51, 647217.10, 3500.00],
    [285169.05, 522357.20, 10.00],
    [126858.21, 185190.59, 0],
]

Desired result:

Array
(

    [0] => "201767.11, 349399.51, 285169.05, 126858.21",
    [1] => "514324.91, 647217.10, 522357.20, 185190.59",
    [2] => "73205.74, 3500.00, 10.00,0"

)


Solution 1:[1]

Just extract each column incrementally and join it. This only works with sub-arrays as shown with 0 based sequential indexes:

$i = 0;
while($new = array_column($array, $i)) {
    $result[] = implode(', ', $new);
    $i++;
}

For other non-0 based, non-sequential, non-integer, just re-index the sub-arrays before extracting and joining:

$array = array_map(function($v) { return array_values($v); }, $array);

Solution 2:[2]

use can use array_map

$arr = array_map(null, ...$arr);
$temp = array_map(function($item){
    return implode(", ", $item);
},$arr);

Output:

Array
(
    [0] => 201767.11, 349399.51, 285169.05, 126858.21
    [1] => 514324.91, 647217.1, 522357.2, 185190.59
    [2] => 73205.74, 3500, 10, 0
)

Demo.

If you want to use one-liner

$temp = array_map(function ($item) {return implode(", ", $item); }, array_map(null, ...$arr)); 

Demo.

Notice the use of array_map with null to group the sub-arrays fetching nth index of every subarray.

... splat operator we use it to expose as arguments to the function.

Reference: implode, array-map

Solution 3:[3]

The task of transposing and imploding can be done within one call of array_map(). Spreading the $array with ... and feeding it to array_map() will effectively isolate columns of data -- each column will be imploded within the anonymous function body.

Code: (Demo)

$array = [
    [201767.11, 514324.91, 73205.74],
    [349399.51, 647217.10, 3500.00],
    [285169.05, 522357.20, 10.00],
    [126858.21, 185190.59, 0],
];

var_export(array_map(fn() => implode(', ', func_get_args()), ...$array));

Or consolidate the column data with another spread operator (Demo)

var_export(array_map(fn(...$column) => implode(', ', $column), ...$array));

Output (from either approach):

array (
  0 => '201767.11, 349399.51, 285169.05, 126858.21',
  1 => '514324.91, 647217.1, 522357.2, 185190.59',
  2 => '73205.74, 3500, 10, 0',
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 mickmackusa