-1

我遇到了一个函数问题,该函数应该返回一个 certian 对象的所有子对象并将整个事物编码为 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 );
}

任何帮助都是极好的。谢谢。

4

1 回答 1

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”检查移至查询
于 2012-10-12T22:00:46.343 回答