Home > Article > Backend Development > How to Transpose a 2D Array and Convert it into a String?
Transpose 2D Array and Convert to String
The given 2D array can be transposed into a string by combining the transposed rows with commas and joining the resultant rows with pipes.
Solution:
Assuming a 2D array named array stored as:
array = [[01, 03, 02, 15], [05, 04, 06, 10], [07, 09, 08, 11], [12, 14, 13, 16]]
To transpose this array, we can use a nested loop:
tmpArr = [] for sub in array: tmpArr.append(','.join(sub)) result = '|'.join(tmpArr) print(result)
This code will output:
01,05,07,12|03,04,09,14|02,06,08,13|15,10,11,16
This code creates a temporary array tmpArr by iterating over each sublist in array and joining its elements with commas. Finally, it joins the elements of tmpArr with pipes to produce the desired string.
The above is the detailed content of How to Transpose a 2D Array and Convert it into a String?. For more information, please follow other related articles on the PHP Chinese website!