Skip to content

Instantly share code, notes, and snippets.

@refo
Last active October 12, 2015 22:27
Show Gist options
  • Save refo/542ed8a8940303ba9998 to your computer and use it in GitHub Desktop.
Save refo/542ed8a8940303ba9998 to your computer and use it in GitHub Desktop.
<?php
//class FlightTree implements ArrayAccess, Traversable {
class FlightTree {
private $key;
private $data = NULL;
private $children = array();
private $parent;
public function __construct($key = NULL, $data = NULL, $parent = NULL)
{
$this->key = $key === NULL ? 'root' : $key;
$this->data = $data;
$this->parent = $parent;
}
public function createChild($key = NULL, $data = NULL)
{
$class = __CLASS__;
return new $class($key, $data, $this);
}
public function getChild($key)
{
if (isset($this->children[$key])) {
return $this->children[$key];
}
}
private function childAddedEvent($child, $price)
{
// örnek event
//
if (! is_array($this->data)) {
$this->data = array(
'price_min' => $price,
'price_max' => $price,
);
}
$this->data['price_min'] = min($price, $this->data['price_min']);
$this->data['price_max'] = max($price, $this->data['price_max']);
}
public function insert($keys, $price)
{
// ilk key'i array'den ayır
$childName = array_shift($keys);
$child = NULL;
// aynı id ile child varsa, onu kullan
if (isset($this->children[$childName]))
{
$child = $this->children[$childName];
}
// bu id ilk defa giriyorsa, yeni oluştur ve child olarak ekle
else {
$child = $this->createChild($childName, $price);
$this->children[$child->key] = $child;
}
$this->childAddedEvent($child, $price);
// ilk key'i ayrılmış array'de eklenecek key kaldıysa,
// kalan key'leri recursive olarak işle
if (0 < count($keys)) {
$child->insert($keys, $price); // !! recurse
}
}
public function asArray($filter = array())
{
$arr = array(
'key' => $this->key,
'data' => $this->data,
);
if (0 < count($this->children)) {
$arr['children'] = array();
if (empty($filter)) {
foreach($this->children as $child) {
$arr['children'][] = $child->asArray(); // !! recurse
}
} else {
$childName = array_shift($filter);
return $this->getChild($childName)->asArray($filter); // !! recurse
}
}
return $arr;
}
}
/*
//*/
$obj = [
[
'ids' => [
'A1',
'B1',
'C1',
],
'price' => 70
],
[
'ids' => [
'A1',
'B2',
'C1',
],
'price' => 71
],
[
'ids' => [
'A1',
'B2',
'C2',
],
'price' => 75
],
[
'ids' => [
'A2',
'B3',
'C2',
],
'price' => 77
],
[
'ids' => [
'A2',
'B3',
'C2',
],
'price' => 80
],
[
'ids' => [
'A1',
'B1',
'C3',
],
'price' => 60
],
[
'ids' => [
'A3',
'B4',
'C3',
],
'price' => 55
],
];
$tree = new FlightTree;
foreach($obj as $o) {
$tree->insert($o['ids'], $o['price']);
}
print_r($tree->asArray(array('A1')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment