$strs = array(
array(
"id"=>1,
"str"=>'A',
"children"=>array(
array(
"id"=>2,
"str"=>'B',
"children"=>array(
"id"=>3,
"str"=>'C',
"children"=>array(
)
)
),
array(
"id"=>4,
"str"=>'D',
"children"=>array(
)
),
)
)
);像这样的tree格式 同级之间用or来连接 上下级之间用and连接
最终需要返回 A and ((B and C) or D)
卡在这里有大半天了 求助各位高手支个招
"id"=>1,
"str"=>'A',
"children"=>array(
array(
"id"=>2,
"str"=>'B',
"children"=>array(
"id"=>3,
"str"=>'C',
"children"=>array(
)
)
),
array(
"id"=>4,
"str"=>'D',
"children"=>array(
)
),
)
);echo foo($strs);function foo($ar) {
$r[] = $ar['str'];
if($ar['children']) {
if(key($ar['children']) !== 0) $r[] = foo($ar['children']);
else {
$p = array();
foreach($ar['children'] as $t) $p[] = foo($t);
$r[] = '(' . join(' or ', $p) . ')';
}
}
if(count($r) == 1) return $r[0];
return '(' . join(' and ', $r) . ')';
}(A and ((B and C) or D))
我array写错了
正确的格式如下
$strs = array(
array(
"id"=>1,
"str"=>'A',
"children"=>array(
array(
"id"=>2,
"str"=>'B',
"children"=>array(
array(
"id"=>3,
"str"=>'C',
"children"=>array(
)
)
)
),
array(
"id"=>4,
"str"=>'D',
"children"=>array(
)
),
)
)
);
private function buildstr($strs){
$sqlstr = '';
$sql = array();
foreach($strs as $key=>$str){
$temp = $str['str'] . '[!'.$str['id'].'!]';
if(count($str['children'])){
$substr = $this->buildstr($str['children']);
$sql[$key] = str_replace('[!'.$str['id'].'!]',' and '.$substr,$temp);
}else{
$sql[$key] = str_replace('[!'.$str['id'].'!]','',$temp);
}
}
if(count($sql)>1){
$sqlstr = '( ( '.join(' ) or ( ',$sql).' ) )';
}else{
$sqlstr = $sql[0];
}
return $sqlstr;
}