5lackp1x3l0x17
5lackp1x3l0x17

Reputation: 349

Creating 2-D matrix in php

The thing is I have to create a 2D matrix in php where each row and column must have a key. I tried to do this but what happens is that a 2-D array is created which does not resemble a matrix. I used the following code:

$x=$row['start_id'];
$y=$row['dest_id'];
$d=$row['distance'];
$this->map[$x][$y]=$d;

Here map is the intended matrix. The intention of this code is to create an adjacency matrix and then fill the unset cells with maximum distance. $x, $y and $d in above code are derived from result of a mysql query.

Sample Output:

Array (
    [10010012] => Array ( 
        [10010013] => 2
        [10010016] => 8 
    )
    [10010016] => Array ( 
        [10010015] => 5 
    )
    [10010013] => Array ( 
        [10010014] => 7 
        [10010016] => 3
    )
    [10010014] => Array ( 
        [10010015] => 2 
    )
)

Now the problem is that I am not able to fill the empty cells
e.g. row key =>[10010012] and column key=>[10010015] (Not able to set value)

Any help is appreciated. If possible also mention how to traverse through such matrices.

I am a relative beginner and have tried my best to explain my problem. However if you find any shortcomings please point them out.

Edit: The matrix is not a square one.

Upvotes: 2

Views: 16182

Answers (1)

VolkerK
VolkerK

Reputation: 96159

That would be

$this->map[10010012][10010015]= MAX_DISTANCE;

On the other hand, why do you want to set all empty/non-existing cell to MAX_DISTANCE? You can leave the map incomplete and whenever a cell does not exist you assume MAX_DISTANCE as its value.

edit: simple example

define('MAX_DISTANCE', PHP_INT_MAX);

$map = array(
  10010012 => array ( 10010013 => 2, 10010016 => 8),
  10010016 => array ( 10010015 => 5 ),
  10010013 => array ( 10010014 => 7, 10010016 => 3),
  10010014 => array ( 10010015 => 2 )
);

function getValue(&$map, $x, $y) {
  return isset($map[$x][$y]) ? $map[$x][$y] : MAX_DISTANCE;
}

function setValue(&$map, $x, $y, $value) {
  if ( !isset($map[$x]) ) {
    $map[$x] = array($y => $value);
  }
  else {
    $map[$x][$y] = $value;
  }
}

// get an "existing" value from $map
echo getValue($map, 10010012, 10010016), "\n";
// get a "non-existing" value from $map
echo getValue($map, 10010014, 10010016), "\n";

// set a "new" value
setValue($map, 10010014, 10010016, 5);
// $map has been altered
var_dump($map[10010014]);

prints

8
2147483647
array(2) {
  [10010015]=>
  int(2)
  [10010016]=>
  int(5)
}

Upvotes: 6

Related Questions