从php数组中清除空值

时间:2012-10-12 21:44:27

标签: php arrays function null

我遇到了一个函数的问题,该函数应该返回一个certian对象的所有childern并将整个事件编码为JSON。目前它正在工作,但JSON编码中有一堆空值,我尝试了array_filter()foreach循环来擦除它们,两者都不起作用。

findChildren($conn, $topic);

$data = array();
function findChildren($conn, $topic) {
   $rst = $conn->query("SELECT topicID, topicTitle, topicParentID, topicDeleted FROM tbl_topics WHERE topicParentID = $topic");
   while ($row = $rst->fetch_assoc()) {
      if ($row['topicDeleted'] == 0) {
         //$data[] = htmlentities($row, UTF-8);
         if($row != '') {
            $data[] = $row;   
         }

         findChildren($conn, $row['topicID']);
      }              
   }
   echo json_encode( $data );
}

任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:0)

<?php

$data = findChildren($conn, $topic);
echo json_encode($data);

function findChildren($conn, $topic) {
    $data = array();
    $rst  = $conn->query(
        "
            SELECT topicID, topicTitle, topicParentID, topicDeleted
            FROM tbl_topics
            WHERE topicParentID = ${topic} and topicDeleted = 0
        "
    );

    while ($row = $rst->fetch_assoc()) {
        $data[] = array_filter($row);

        if(!empty($row['topicID'])) {
            $data = array_merge(
                $data,
                findChildren($conn, $row['topicID'])
            );
        }
    }

    return $data;
}
  • 更改了函数以返回数组,而不是直接回显,或者使用变量,就像它是全局
  • 一样
  • 将'topicDeleted'检查移至查询