Reputation: 1141
I have this code in php.
public function display_children($parent,$level){
try {
$cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?');
$cmd->execute(array($parent));
while ( $row = $cmd->fetch(PDO::FETCH_ASSOC)) {
$rec[] = [['v' => $row['mem'], 'f' => $row['mem']], (string)$row['pid'], $row['mem']];
$this->display_children($row['mem'], $level + 1);
}
echo json_encode(rec);
}
catch(PDOException $ex){
return $ex->getMessage();
}
}
And this is the result in my ajax
[][][[{"v":"9","f":"9"},"7","9"],[{"v":"10","f":"10"},"7","10"]][][[{"v":"7","f":"7"},"5","7"],[{"v":"8","f":"8"},"5","8"]]
I want to remove those empty array to be like this.is it possible ?
[[{"v":"9","f":"9"},"7","9"],[{"v":"10","f":"10"},"7","10"],[{"v":"7","f":"7"},"5","7"],[{"v":"8","f":"8"},"5","8"]]
I tried to use this to remove the empty array but it failed to remove.
$rec = array_filter($rec);
Thank you in advance.
Upvotes: 0
Views: 93
Reputation: 49
Try something like this:
public function display_children($parent,$level, $rec = array()){
try {
$cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?');
$cmd->execute(array($parent));
while ( $row = $cmd->fetch(PDO::FETCH_ASSOC)) {
$rec[] = [['v' => $row['mem'], 'f' => $row['mem']], (string)$row['pid'], $row['mem']];
$rec = $this->display_children($row['mem'], $level + 1, $rec);
}
}
catch(PDOException $ex){
//return $ex->getMessage();
return $rec;
}
return $rec;
}
First call:
echo json_encode(display_children(5, 0));
Upvotes: 1
Reputation: 161
you can use array_filter to do this.
function filter($var){
return !empty($var);
}
$array1 = array("a"=>null, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$newarray = array_filter($array1, "filter"));
result: Array ( [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
Upvotes: 2