How to Transpose a 2D Array and Convert it to a Comma-Separated Column, Pipe-Separated Row String?

Susan Sarandon
Release: 2024-10-28 12:49:02
Original
624 people have browsed it

How to Transpose a 2D Array and Convert it to a Comma-Separated Column, Pipe-Separated Row String?

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

Desired Output:

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

Solution:

This task can be accomplished in two steps:

  1. Transpose the Array:

    • Create a new array where the original rows become columns, and vice versa.
  2. Create the String Representation:

    • Iterate over each row of the transposed array.
    • Join the elements of each row with commas (,).
    • Join the rows with a pipe character (|).

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!