Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6251277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T13:35:08+00:00 2026-05-24T13:35:08+00:00

I have a simple recursive array function that looks like this: function recursive_array($results) {

  • 0

I have a simple recursive array function that looks like this:

function recursive_array($results) {
    global $DBH;
    if (count($results)) {
        echo $res - > Fname;
        foreach($results as $res) {
            $STH = $DBH - > query("SELECT FID,FParentID,Fname FROM list WHERE FParentID  = ".$res - > FID."");
            $fquerycount = $STH - > rowCount();
            $STH - > setFetchMode(PDO::FETCH_OBJ);
            recursive_array($STH);
        }
    }
}


$FID = isset($_GET['FID']) ? $_GET[' FID'] : 0;
$STH = $DBH - > query("SELECT FID,FParentID,Fname FROM list WHERE FParentID ='0' ");
$STH - > setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH);

I also have created a simple query class that looks like this:

class queryloop {
    function __construct($args) {
        global $DBH;
        $table = $args['tbl'];
        if (array_key_exists('orderby', $args)): $orderby = 'ORDER BY '.$args['orderby'];
        else: $orderby = '';endif;
        if (array_key_exists('groupby', $args)): $groupby = 'GROUP BY '.$args['groupby'];
        else: $groupby = '';endif;
        if (array_key_exists('start', $args)): unset($orderby);$start = $args['start'].' , ';
        else: $start = '';endif;
        if (array_key_exists('limit', $args)): $limit = 'LIMIT '.$start.' '.$args['limit'];
        else: $limit = '';endif;
        // UNSET the previously used array keys so they are not use again to create the query string
        unset($args['tbl']);
        unset($args['orderby']);
        unset($args['groupby']);
        unset($args['start']);
        unset($args['limit']);
        // Checks if args still an array after UNSET above.  If not empty create the query string
        if (!empty($args)): foreach($args as $k = > $v): $querystr. = 'AND '.$k.' = \''.$v.'\'';endforeach;
        // If args array empty return empty query string
        else: $querystr = '';endif;$STH = $DBH - > query("SELECT * FROM ".$table." WHERE key = '".KEY."'  ".$querystr."  ".$groupby." ".$orderby."  ".$limit." ");
        if ($STH): $STH - > setFetchMode(PDO::FETCH_OBJ);
        while ($row = $STH - > fetch()): foreach($row as $key = > $val):
        // check if value is numeric //        
        if (is_numeric($row - > $key)): $data[$row - > ID][$key] = $row - > $key;
        // check if value is array //
        elseif(is_array($row - > $key)): $data[$row - > ID][$key] = $row - > $key;
        // check if value is not numeric or array convert to html entities //
        else: $data[$row - > ID][$key] = htmlentities($row - > $key);endif;endforeach;endwhile;$this - > data = json_encode($data); // return json array if data
        else: $this - > data = ''; // return 'null' if no data
        endif;
    }
}

$args = array('tbl' = > 'atable', 'limit' = > '5', 'start' = > '200', 'orderby' = > 'ID DESC');
$loop = new queryloop($args) // run the loop etc.

How do I turn my recursive array into something like the class queryloop so that I can “pull out” json endoded data I know that this (below) is totally wrong but what ever I do I cannot get a correctly formed json array or even anything to return form my attempted class below. Help would be much appreciate. Thanks in advance.

class recloop {
    function __construct() {}

    function recursive_array($results) {
        global $DBH;
        if (count($results)) {
            foreach($results as $res) {
                echo $res - > Name;
                $STH = $DBH - > query("SELECT * FROM atable WHERE ParentID  = ".$res - > ID."");
                $fquerycount = $STH - > rowCount();
                $STH - > setFetchMode(PDO::FETCH_OBJ);
                recursive_array($STH);
            }
        }
    }

    function recursive_start() {
        global $DBH;
        $ID = isset($_GET['ID']) ? $_GET['ID'] : 0;
        $STH = $DBH - > query("SELECT * FROM atable WHERE ParentID  = '".$ID."' ");
        $STH - > setFetchMode(PDO::FETCH_OBJ);
        recursive_array($STH);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T13:35:09+00:00Added an answer on May 24, 2026 at 1:35 pm

    How do I turn my recursive array into something like the class queryloop so that I can “pull out” json endoded data I know that this (below) is totally wrong but what ever I do I cannot get a correctly formed json array or even anything to return form my attempted class below. Help would be much appreciate. Thanks in advance.

    To answer your question, I would say it’s not specific if you encapsulate your routines into objects or not that much, but that you take care that each object is there for a sole purpose. For example:

    • One object is fetching the data from the database.
    • One object/composite/array is the data-structure, representing the data.
    • One object or function is taking over the job to convert/encode the data into json.

    Within your code I see that you right now are only running SQL-queries. The data fetched from the database server is not stored into a return variable at all, it get’s directly consumed while being recursively processed. I assume you do this for debugging reasons.

    So the actual question is, what do you want to do? You write that you want to encode an object into json output, which is perfectly possible with json_encodeDocs, however I think you refer to some specific data, like the entity (data) of the most parentId or something.

    Following is some mock-up code based on your code for reading purposes (not tested, must not match your needs) that can provide all parent objects of that one specified by ID by using recursion. The recursion has been criticised because this can result in running a lot of queries – and additionally there is risk to create an endless loop which will result in a recursion stack overflow – your program crashes then.

    To handle that alternatively, this is bound to the database design (which should be done before the design of the code, and I don’t know your database design nor what you actually want to do, so I can’t add assumptions for that). So the following code takes care of already queried objects only while still using recursion as the strategy to query your database.

    For the actual data-structure I opted for an array of plain old PHP objects, keyed by the ID field from the database (which I assume that it exists per record):

    /**
     * HTTP Get Parameter (Input)
     */
    class HTTPGetParameter {
        private $name;
        private $default;
        public function __construct($name, $default = '') {
            $this->name = (string) $name;
            $this->default = (string) $default;   
        }
        /**
         * @return string
         */
        public function getValue()
        {
            return isset($_GET[$name]) ? $_GET[$name] : $this->default;
        }
        /**
         * @return int
         */
        public function getValueInt()
        {
            return (int) $this->getValue();
        }
        /**
         * @link http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
         */
        public function __toString()
        {
            return $this->getValue();
        }
    }
    
    /**
     * Data Provider
     */
    class PDODataProvider
    {
        private $pdo;
        public function __construct(PDO $pdo)
        {
            $this->pdo = $pdo;
        }
        /**
         * @return array
         */
        public function findAllATableParents($id)
        {
            return $this->findAllOn('atable', 'ParentID', $id);
        }
        public function findAllBTableParents($id)
        {
            return $this->findAllOn('btable', 'ParentID', $id);
        }
        private function findAllOn($table, $field, $id)
        {
            $id = (int) $id;
    
            $objects = array();
    
            $sql = sprintf("SELECT * FROM %s WHERE %s  = '%d'", $table, $field, $id);
            $pdoStatement = $this->pdo->query($sql);
            $pdoStatement->setFetchMode(PDO::FETCH_OBJ);
    
            foreach($pdoStatement as $parent)
            {
                 $parentId = $parent->ID;
    
                 # parents that had been queried are skipped
                 if (isset($objects[$parentId]))
                     continue;
    
                 $objects[$parentId] = $parent;
    
                 # add parent objects by recursion
                 $objects += $this->findAllParents($parentId);
            }
            return $objects;
        }
    }
    
    
    /**
     * main
     */
    $data = new PDODataProvider($DBH);
    
    $id = new HTTPGetParameter('ID', 0);
    
    $objects = $data->findAllParents($id->getValueInt());
    
    echo json_encode($objects);
    

    I hope this example is helpful for you to answer your question.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple recursive function RCompare() that calls a more complex function Compare()
I have simple HTML code with some JavaScript. It looks like: <html> <head> <script
I have a rather annoying issue that I solved using a simple recursive method
I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression
I have simple win service, that executes few tasks periodically. How should I pass
I'd like to see the .tail IL instruction, but the simple recursive functions using
I have a multidimensional associative array, and I want to apply array_walk_recursive so that
I have this function (sample here: http://jsbin.com/emabe4/ ) var a=[]; var log = document.getElementById('log');
I have just started looking at javascript so hopefully this will be something simple.
Ok so I have an array that holds the following elements: $array['a']['b'][0]['c']; $array['a']['b'][1]['c']; $array['a']['d'][0]['c']['c'];

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.