Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose rows and columns in a 2D array [duplicate]

Tags:

php

I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

    //Creating rows and columns for text file
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

My first table displays as expected and looks somthing like this:

1 2 3 4 5
6 7 8 9 10

I need it to appear as such (i.e rotating the position of the rows and columns):

1 6
2 7
3 8
4 9
5 10

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

like image 832
Aaron Martin Avatar asked Dec 08 '17 16:12

Aaron Martin


People also ask

How do you find duplicates in a 2D array?

Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.

How do you swap rows in a 2D array?

The key to swap 2 rows in a 2 dimension array is to first loop through the 2 dimensional array and then swap the position of first row to the second row.


1 Answers

This should give you what you need.

function transpose($array_one) {
    $array_two = [];
    foreach ($array_one as $key => $item) {
        foreach ($item as $subkey => $subitem) {
            $array_two[$subkey][$key] = $subitem;
        }
    }
    return $array_two;
}

Then just pipe your existing array into the function and render the resulting array.

like image 148
Bryant James Avatar answered Nov 24 '22 04:11

Bryant James