我的问题是:
如何将下面的PHP数组代码转换为更灵活,精简和平均面向对象的代码?
我尝试过很多东西,包括PHP的SPL。不幸的是,我们仍在使用PHP 5.2.3,这意味着还没有几个方便的SPL功能。 升级到PHP 5.3.x.不是一种选择。
// $data array that comes from a SQL result
Array
(
[0] => Array
(
[parentID] => 115
[childID] => 1718
[some_attr] => 146
)
[1] => Array
(
[parentID] => 121
[childID] => 1301
[some_attr] => 105
)
[2] => Array
(
[parentID] => 121
[childID] => 1300
[some_attr] => 2
)
)
使用以下代码我创建了一个这样的数组:
// $children array
Array
(
[115] => Array
(
[0] => Array
(
[childID] => 1718
[some_attr] => 146
)
)
[121] => Array
(
[1] => Array
(
[childID] => 1301
[some_attr] => 105
)
[2] => Array
(
[childID] => 1300
[some_attr] => 2
)
)
)
上面创建父树数组的代码:
// $data array is populated from a SQL query
$children = array();
foreach ($data as $key=>$row) {
$parent = (int)$row['parentID'];
if( !isset($children[$parent]) ) {
$children[$parent] = array();
}
// Remove parent id, because we already have it as a key in the array
unset($row['parentID']);
$children[$parent][$key] = $row;
}
这是我到目前为止所提出的。
// ParentContainer
class ParentObject {
public $parentID;
public $children = array();
}
// The actual tree: parent-child relationships
// parent
// |
// |___ child 1
// |___ child 2
class Tree_alpha {
/**
* @var int $parent //parent is the key for this node
*/
public $parent;
public $parentObject;
/* Child Nodes */
protected $children = array();
// Data for the node
protected $data;
public function __construct($parent = null, $data = null) {
$this->parent = $parent;
$this->data = $data;
$this->parentObject = new ParentObject();
}
public function addChild($parent, $key, $data = null) {
if (!$this->parentObject = $this->findParent($parent) ) {
$this->children = array();
}
unset($data['parentID']);
$this->parentObject->parentID = $parent;
$this->parentObject->children[$parent][$key] = $data;
}
public function findParent($parent) {
if ($this->parentObject->parentID == $parent) {
return $this->parentObject;
} else {
return new ParentObject();
}
//return isset($children[$parent]);
}
}
感谢任何帮助。