Transposing a 2D Array and Converting it to a String with Comma-Separated Columns and Pipe-Separated Rows
Given a multidimensional array, transpose it to convert columns into rows. Additionally, generate a string representation of the transposed array, where each row is separated by a pipe character ('|'), and elements within each row are separated by commas (,).
Example:
Consider the following 2D array:
01 03 02 15 05 04 06 10 07 09 08 11 12 14 13 16
Desired Output:
01,05,07,12|03,04,09,14|02,06,08,13|15,10,11,16
Solution:
This task can be accomplished in two steps:
Transpose the Array:
Create the String Representation:
JavaScript Implementation:
<code class="javascript">// Transpose the array const transposedArray = originalArray.map((row, i) => row.map((el, j) => originalArray[j][i])); // Create the string representation const result = transposedArray.map(row => row.join(",")).join("|");</code>
PHP Implementation:
<code class="php">// Transpose the array $transposedArray = array(); foreach ($originalArray as $row) { foreach ($row as $key => $value) { $transposedArray[$key][] = $value; } } // Create the string representation $result = array_map(function($row) { return implode(",", $row); }, $transposedArray); $result = implode("|", $result);</code>
The above is the detailed content of How to Transpose a 2D Array and Convert it to a Comma-Separated Column, Pipe-Separated Row String?. For more information, please follow other related articles on the PHP Chinese website!