Transpose and Format 2D Array
In the realm of data manipulation, it becomes necessary to reshape and format arrays for efficient presentation. Consider the task of transposing a two-dimensional array and joining its elements with specific delimiters.
Given the following array:
01 03 02 15 05 04 06 10 07 09 08 11 12 14 13 16
The objective is to convert it to a string with the following format:
01,05,07,12|03,04,09,14|02,06,08,13|15,10,11,16
where the columns are converted to rows and the elements within each row are separated by commas, with the rows separated by pipes.
Solution using PHP
To accomplish this task in PHP, we can employ the following steps:
Here's the code snippet:
<code class="php">$array = array( array('01', '03', '02', '15'), array('05', '04', '06', '10'), array('07', '09', '08', '11'), array('12', '14', '13', '16') ); $tmpArr = array(); foreach ($array as $sub) { $tmpArr[] = implode(',', $sub); } $result = implode('|', $tmpArr); echo $result;</code>
The above is the detailed content of How to Transpose and Format a 2D Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!