"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Transpose and Format a 2D Array in PHP?

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

Published on 2024-11-09
Browse:483

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:

$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;
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3