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