在2D数组中转置行和列

时间:2017-12-08 16:42:28

标签: php

我创建了一个表格,在表格中显示一系列数字。我试图使用for每个循环和一个名为transpose_matrix的函数来转置矩阵(翻转行和列),但它似乎并不适合我。我哪里错了?我正在使用以下代码:

1 2 3 4 5
6 7 8 9 10

我的第一张表按预期显示,看起来像这样:

1 6
2 7
3 8
4 9
5 10

我需要它这样出现(即旋转行和列的位置):

charArray

我在StackOverflow上搜索过类似的问题或解决方案,但似乎无法找到有效的问题或解决方案。我对PHP也很陌生,如果它是一个简单的修复,那么道歉

4 个答案:

答案 0 :(得分:1)

请检查:https://3v4l.org/OnuSu

$table = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
];

$i         = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
    $transpose[] = $columns;
}

$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
    $cols = count($transpose[$i]);
    $table .= '<tr>';
    for ($j = 0; $j < $cols; $j++)
    {
        $table .= '<td>' . $transpose[$i][$j] . '</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';
echo $table;

答案 1 :(得分:0)

您可以逐个提取子数组的列:

$external_variable = TRUE;
usort($array, function($a, $b) {
    // do sorting stuff based on $external_variable
});

然而,这可能更好,即使每个数组中的键不同,也应该有效:

foreach(reset($result) as $key => $values) {
    $transpose[] = array_column($result, $key);
}

答案 2 :(得分:0)

您的功能似乎工作正常,您只需要调用它。

在功能下面添加:

//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
    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;
}

$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($mat as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";

答案 3 :(得分:-1)

这应该可以满足您的需求。

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

然后只需将现有数组传输到函数中并渲染结果数组。