Skip to content
Advertisement

Transpose 2d array, join second level with commas, and join first level with pipes

I have the following two-dimensional array:

01 03 02 15
05 04 06 10
07 09 08 11
12 14 13 16

I want to convert columns to rows then reduce the matrix to a string like the following:

01,05,07,12|03,04,09,14|02,06,08,13|15,10,11,16

Advertisement

Answer

I’m assuming that you have this array:

$array = array (
  array ('01','03','02','15'),
  array ('05','04','06','10'),
  array ('07','09','08','11'),
  array ('12','14','13','16')
);

In which case, you can do this:

$tmpArr = array();
foreach ($array as $sub) {
  $tmpArr[] = implode(',', $sub);
}
$result = implode('|', $tmpArr);
echo $result;

See it working

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement