Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 382
smith Avatar asked Jun 03 '26 20:06

smith


1 Answers

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

like image 108
DaveRandom Avatar answered Jun 06 '26 23:06

DaveRandom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!