1
Let’s assume I have a matrix this way:
$matrix = [[0, 1, 1, 0],
[1, 1, 1, 0],
[1, 0, 0, 0]];
Imagine that you are making a loop and capturing the position of this matrix as the example below, being y the lines with my arrays and x the positions of each line (I do not know if it is correct the way to build it):
<?php
$data = getHierarchyMatrix(['x'=>2,'y'=>1], $matrix);
echo '<pre>';
print_r($data);
function getHierarchyMatrix($currentXY, $matrix) {
$currentX = $currentXY['x'];
$currentY = $currentXY['y'];
foreach ($matrix as $currentLine => $arrayLine) {
if ($currentLine >= $currentY) {
$previousY = ($currentLine-1);
$nextY = ($currentLine+1);
if (isset($matrix[$previousY])) {
$previousValueY = $matrix[$previousY];
}
if (isset($matrix[$currentLine+1])) {
$nextValueY = $matrix[$nextY];
}
foreach ($arrayLine as $current => $value) {
if ($current == $currentX) {
$currentValue = $value;
$previousX = ($current - 1);
if (isset($matrix[$current][$previousX])) {
$previousValueX = $matrix[$current][$previousX];
}
$nextX = ($current + 1);
if (isset($matrix[$current][$nextX])) {
$nextValueX = $matrix[$current][$nextX];
}
}
}
}
}
return [
'atual' => $currentValue,
'esquerda' => $previousValueX,
'direita' => $nextValueX,
'em cima' => $previousValueY,
'em baixo' => $nextValueY
];
}
The problem is basically to take the x and y position and the 4 elements that surround them, I don’t know if I’m doing this directly... but I need to make the quadrant based on the current position, how could I do that? I don’t think my method is very well developed. Maybe there is some way to do this using some PHP function that I don’t know, someone could help me... Its that there are methods that could aid in this, as:
$atual = current($array);
$proximo = next($array);
$anterior = prev($array);
$ultimo = end($array);
Obs: I will also need this formula for a Javascript version
Can’t you take the elements using the position of the element itself as a reference? For example, suppose the element is in
1,1
. The elements you seek are in0,1
,1,0
,2,1
and1,2
.– Rodrigo Rigotti
Rola, I just don’t know how to do it. But in the example I’m already getting the position of the element itself.
– Ivan Ferrer
@Rodrigorigotti, thanks also for the reply. Helped to reflect on everything.
– Ivan Ferrer