如何删除空数组

时间:2014-12-15 06:33:03

标签: javascript php json

我在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();
      }

  }

这是我的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"]]

我想删除那些空数组,这样可能吗?

[[{"v":"9","f":"9"},"7","9"],[{"v":"10","f":"10"},"7","10"],[{"v":"7","f":"7"},"5","7"],[{"v":"8","f":"8"},"5","8"]]

我尝试使用它删除空数组,但无法删除。

 $rec = array_filter($rec);

提前谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用array_filter执行此操作。

function filter($var){
  return !empty($var);
}

$array1 = array("a"=>null, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

$newarray = array_filter($array1, "filter"));

结果: 排列 (     [b] => 2     [c] => 3     [d] => 4     [e] =>五 )

答案 1 :(得分:1)

尝试这样的事情:

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

第一个电话:

echo json_encode(display_children(5, 0));