简体   繁体   中英

How can I remove empty array

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.

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 )

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM