Invert matrix numbers - loop
First, i have these values.
$Arr1 = array(1/1, 1/2, 3/1);
$Arr2 = array(1/1, 4/1);
$Arr3 = array(1/1);
and i need an output with 3 arrays like these:
$a1 = array (1/1, 1/2, 3/1);
$a2 = array (2/1, 1/1, 4/1);
$a3 = array (1/3, 1/4, 1,1);
What i am 开发者_运维百科trying is :
for ($i=0; $i<count($Arr1); $i++) {
${"a".$i} = array(
//here, the number of array elements depends to the length of $a1
);
}
Any help ? thanks
I think this image helps to understand the problem:
First off, using a 2D array will make your life a lot easier.
So first, initialize your values like this:
$matrix_size = 3;
$matrix = array();
for($i = 0; $i < $matrix_size; $i++){
$matrix[$i] = array_fill(0, $matrix_size, null);
}
$matrix[0][0] = 1/1;
$matrix[0][1] = 1/2;
$matrix[0][2] = 3/1;
$matrix[1][1] = 1/1;
$matrix[1][2] = 4/1;
$matrix[2][2] = 1/1;
Then you can run a loop like this:
foreach($x = 0; $x < $matrix_size; $x++){
foreach($y = 0; $y < $matrix_size; $y++){
if(is_null($matrix[y][x]) && !is_null($matrix[x][y])){
$matrix[y][x] = 1/$matrix[x][y];
}
}
}
I'm sure there is a much more efficient way to do this, but this is a start for you to explore.
精彩评论