Home > Backend Development > PHP Tutorial > How to Transpose and Concatenate Elements in a Multidimensional Array?

How to Transpose and Concatenate Elements in a Multidimensional Array?

Susan Sarandon
Release: 2024-10-28 18:54:29
Original
422 people have browsed it

How to Transpose and Concatenate Elements in a Multidimensional Array?

Transpose and Concatenate Multidimensional Array Elements

Given a two-dimensional array, the task is to transpose its elements, join elements within rows with commas, and join rows with pipes to create a single string.

Problem:

Consider the following two-dimensional array:

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

The goal is to convert this array into a string with the following format:

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

Solution:

To achieve this, we can follow these steps:

  1. Use foreach loop to iterate over each sub-array within the original array.
  2. Within each iteration, use implode() with a comma as the separator to concatenate the elements of the sub-array, creating a single string.
  3. Store the resulting strings in a temporary array.
  4. Finally, use implode() again with a pipe as the separator to concatenate the strings in the temporary array, creating the desired output string.

Here's a PHP code snippet that demonstrates the solution:

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

This code will output the desired string in the specified format.

The above is the detailed content of How to Transpose and Concatenate Elements in a Multidimensional Array?. 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