gpt4 book ai didi

php - 循环矩阵值

转载 作者:可可西里 更新时间:2023-11-01 07:45:31 25 4
gpt4 key购买 nike

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

我在表中有这些值:

           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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com