0

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"

)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

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

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

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);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87