Home > Backend Development > PHP Tutorial > How to Transpose a 2D Array and Convert it into a String?

How to Transpose a 2D Array and Convert it into a String?

Barbara Streisand
Release: 2024-10-31 18:54:02
Original
813 people have browsed it

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]]
Copy after login

To transpose this array, we can use a nested loop:

tmpArr = []
for sub in array:
    tmpArr.append(','.join(sub))
result = '|'.join(tmpArr)
print(result)
Copy after login

This code will output:

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template