我在对象数组中存储了数千个URL。我想采用自己构建的类的层次结构,并将其以关联数组的形式放置。但是,当我编写递归函数时,我很难绕开如何使它按我希望的方式工作的大脑。 我的最终目标是将该关联数组转换为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中的数组
答案 0 :(得分:0)
在合并操作中添加一个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;
}