php - 循环矩阵值

标签 php mysql arrays matrix

我有一组值,我需要一个特定的输出:

我在表中有这些值:

           id | value
           1  |  1/4
           2  |  5/1
           3  |  4/1
           4  |  6/1
           5  |  2/1
           6  |  3/1

我正在尝试做的事情:

    A | B   | C   | D   | 
A | 1 | 1/4 | 5/1 | 4/1 | 
B |   | 1   | 6/1 | 2/1 |
C |   |     |  1  | 3/1 |
D |   |     |     | 1   | 

我只有 6 个值,我假装有 10 个值的输出

预期输出:

$matrix[0][0] = 1/1;
$matrix[0][1] = 1/4;
$matrix[0][2] = 5/1;
$matrix[0][3] = 4/1;

$matrix[1][1] = 1/1;
$matrix[1][2] = 6/1;
$matrix[1][3] = 2/1;

$matrix[2][2] = 1/1;
$matrix[2][3] = 3/1;

$matrix[3][3] = 1/1;

我正在尝试这样的事情但没有成功:

while ($sql -> fetch()) {
        for ($i = 0; $i < (//something); $i++) {
            for ($x = 0; $x < (//something); $x++) {
            $matrix[$i][$i+1] = $result;
            }
        }
    }

有什么想法吗?谢谢

最佳答案

请尝试在 php 中实现它。以下是您的逻辑的 Java 代码。

Integer[] singleDim = new Integer[] {2,3, 2};
int matrixSiz = 3;      //this value has to be set manually. 
                    //i didnt get time to find the logic for this 

Integer[][] twoDim = new Integer[matrixSiz][matrixSiz];
int counter = 0;      //this iterates through singleDim array
//logic being done for convesion
for (int i = 0; i < matrixSiz; i++) {
    for (int j = 0; j < matrixSiz; j++) {
        if (i==j) {
            twoDim[i][j]=1;  //setting the diagonal as 1
        }else if (j>i){     // important condition to find the upper part of the matrix
            twoDim[i][j]=singleDim[counter++];
        }
    }
}
//printing it.
for (int i = 0; i < matrixSiz; i++) {
    System.out.println();        //new line
    for (int j = 0; j < matrixSiz; j++) {
        if(twoDim[i][j]==null)
            System.out.print("\t");
        else 
            System.out.print("\t"+twoDim[i][j]);
    }
}

输出

1   2   3
    1   2
        1

上述逻辑应该通过为任何数据更改 singleDimmatrixSiz 来工作。

关于php - 循环矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918505/

相关文章:

MYSQL 重复行的复杂更新

c - 如何删除动态字符数组中的前导空格?

数组中的矛盾指针

php - 自定义网站 VS Drupal/Joomla/Wordpress

php - PHP 数组中的自定义排序 - 类似于 mysql ORDER BY FIELD(order_fied, 4, 1, 5, 2, 3)

php - Websocket具有无限循环循环。它真的比ajax好吗?

php - 使用带有 imagettftext 的字体时出现问题

php - 如何在 PHP 中使用 iText java PDF 库?

javascript - 为什么AJAX发送成功后$_GET总是返回null?

php - 多个 SET 字段使用 LOAD DATA INFILE 作为日期格式