-1

i am having problems with a function that is supposed to return all the childern of a certian object and encode the whole thing into JSON. Currently it is working but there are a bunch of nulls in the JSON encode and i have tried array_filter() and a foreach loop to scrub them out, both didn't work.

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

any help would be awesome. Thanks.

Jeff
  • 21
  • 1
  • 7
  • 1
    please provide a sample json output, and a sample query result. –  Oct 12 '12 at 21:47
  • you're worried about NULLs in the individual columns of $row, correct? – blackcatweb Oct 12 '12 at 21:49
  • Seems that doing this solution on $row would work out. http://stackoverflow.com/questions/3654295/remove-empty-array-elements , although you said you tried array_filter() already. Why didn't that work? – blackcatweb Oct 12 '12 at 21:55
  • `if ($row != '')` doesn't make sense. `$row` is an array, not a string. – Barmar Oct 12 '12 at 21:55
  • 1
    You shouldn't have `echo json_encode($data)` in the function, because it's recursive. Each time it recurses, it echoes the accumulated rows. You shouldn't do that until the outermost call returns. – Barmar Oct 12 '12 at 22:02

1 Answers1

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;
}
  • Changed the function to return an array, rather then echo directly, or use variable as if it was global
  • Moved the 'topicDeleted' checking to the query
rrehbein
  • 4,120
  • 1
  • 17
  • 23