Home  >  Article  >  Backend Development  >  How to Transpose and Format a 2D Array in PHP?

How to Transpose and Format a 2D Array in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 09:56:29726browse

How to Transpose and Format a 2D Array in PHP?

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:

  1. Initialize an empty array $tmpArr to store the formatted rows.
  2. Iterate through each subarray in the original array $array.
  3. For each subarray, concatenate its elements into a single string using implode(',', $sub), and append it to $tmpArr.
  4. Finally, we concatenate the elements in $tmpArr into a string using implode('|', $tmpArr) to obtain the desired result.

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!

Statement:
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