我怎样才能让这个递归的 PHP 函数来创建和关联我的类对象的数组



我有数千个网址存储在一个对象数组中。我想采用我构建的类的层次结构,并将其以关联数组的形式放置。但是,当我编写递归函数时,我很难将我的大脑包裹在如何让它按照我想要的方式工作上。我的最终目标是将此关联数组转换为 json 对象并将其导出。

将我的类对象直接转换为 json 是行不通的,所以这就是为什么我一直在尝试将所有对象属性添加到关联数组中的原因。

//ChildNode class
class ChildNode extends PNode
{
    public $parent;
    public function __construct($url, PNode $parent)
    {
        parent::__construct($url);
        $this->parent = $parent;
    }

    public function getParent()
    {
        return $this->parent;
    }

    public function setParent($parent)
    {
        $this->parent = $parent;
    }

}
//PNode Class
class PNode
{
    public $url;
    public $dir;
    public $children;
    public $title;
    public function __construct($url)
    {
        $this->url = $url;
        $this->children = array();
        $this->dir = parse_url($url, PHP_URL_PATH);
        $html = file_get_html($url);
        $raw = $html->find('title',0);
        $this->title = $raw->innertext;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function setUrl($url)
    {
        $this->url = $url;
    }
    public function getChildren()
    {
        return $this->children;
    }
    public function setChildren($children)
    {
        $this->children = $children;
    }
    public function addChild(ChildNode $childNode){
        $this->children[] = $childNode;
    }

    public function getDir(){
        return $this->dir;
    }
    public function getTitle(){
        return $this->title;
    }
    public function getParent(){
        return $this;
    }



}
//main .php file
//$testArr is an array of PNodes each PNode has an array of ChildNodes
//and a ChildNode can also have an Array of ChildNodes
var_dump(toJson($testArr[0]->getChildren()));
function toJson($arr){
    $temp = array();
    if($arr!=null){
        foreach ($arr as $item){
            $temp[] = ["url"=>$item->getUrl(),"Title"=>$item->getTitle(), "children"=>$item->getChildren()];
            $temp = array_merge($temp, toJson($item->getChildren()));

        }

    }
    else{return $temp;}


}

我收到此警告,但不确定该怎么办。我无法弄清楚如何将临时数组传递给函数,同时将其添加到自身并返回最终结果。

警告:array_merge((:参数 #2 不是 C:\wamp64\www\Scrape v4.0\mainV2 中的数组.php

在合并操作中添加 return 语句:

return array_merge( $temp, toJson( $item->getChildren()));

不要将子项附加到临时数组中,因为无论如何都要递归添加子项。相反,只需添加子计数。

使用 print_r( json_encode( toJson( $testArr))) 的 JSON 输出:

[{"url":"http://abc","Title":null,"ChildCount":1},{"url":"http://abc/a1","Title":null,"ChildCount":0}]

这是修改后的函数:

function toJson( $arr ) {
    $temp = array();
    if ( $arr != null ) {
        foreach ( $arr as $item ) {
            $temp[] = [ "url" => $item->getUrl(), "Title" => $item->getTitle(), "ChildCount" => sizeof($item->getChildren())];
            return array_merge( $temp, toJson( $item->getChildren() ) );
        }
    }
    return $temp;
}

最新更新