0

I wanna create and store graph in php. I have bus schedule, so I decided to create 2 classes:

class Vertex 
{
  public $city_id;
  public $time;
}

class Edge
{
  public routeId;
  public end_vertex;
}

after this I'm trying to fill my graph. It should be something like hashtable where key will be Vertex object and it'll have many edges.

prototype example:

foreach ($data as $route)
{
  $v = new Vertex($route->startCity, $route->startTime)
  if(!graph[$v]) {
    graph[$v] = [];
  }

  graph[$v].add(new Edge($route->routeId, new Vertex($route->city_id, $route->startTime + $route->arrivalTime)));
}

but there is one really big problem, as I understand object cannot be used as array key! Maybe I'm in a wrong way? How to create graphs correctly in php? I'm a newbie in this.

Yekver
  • 4,985
  • 7
  • 32
  • 49

2 Answers2

1

In PHP, only simple types can be used as array indices. Complex types, like arrays, objects and resources do not work properly.

Edit: Oh, if memory serves me right, you should watch out for booleans as well, I seem to recollect an issue I had with them.

Edit2: In your case, the object graph should be pointing at the objects, not an array.

So, for example, your code would look like:

$v = new Vertex();

$v->add(new Edge());

$vertices[] = $v;

Edit3: I noticed some serious syntactic flaws in your code. I don't know the exact reason, but if you really can't get them straight, I would advice that you give the PHP manual a couple of looks.

Edit4: By the way, you are using an object as an array index, not a class. There is no PHP data type for classes, there is only class names, which are plain strings.

Christian
  • 27,509
  • 17
  • 111
  • 155
  • here is one minus in your solution. I can't add check is vertex is already exists and if it is add to it edges. Because of we need to store list of edges inside of vertex obj, so this makes impossible to compare vertex objects. – Yekver Mar 02 '12 at 00:50
  • There's `array_search()` you could use to fix that. It's quite efficient in this situation. – Christian Mar 02 '12 at 07:54
0

See my answer here PHP approach to python's magic __getattr__() and combine it with the __toString() method.

BUT I would off-load this kind of stuff to something like gearman, if it's something more complex.

AND there's a library too http://nodebox.net/code/index.php/Graph

Community
  • 1
  • 1
Flavius
  • 13,566
  • 13
  • 80
  • 126