php - Memory leak in recursive function with reference

383

I got this following code. It's a system to get items and all the children of the children of the children .... of the item. Well, I use a recursive function to do it:

<?php

header('Content-type: application/json; charset=UTF-8');

require_once 'config.php';

function getItems($parent) {
    global $db;

    $itemsStmt = $db->prepare('SELECT * FROM `items` WHERE `parent_id` = ?');
    $itemsStmt->execute(array($parent));
    return $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
}

function addToArray($items, &$array) {    
    foreach ($items as $item) {
        $child = $item['child_id'];
        $indexer = $item['id'];

        $array[$indexer] = array('children' => array());
        $array[$indexer]['definition'] = $item;

        if ($child)
        {
            addToArray(getItems($child), $array[$indexer]['children']);
        }
    }
}

$array = array();

addToArray(getButtons(1), $array);

echo json_encode($array);

The items table looks like this:

id INT PK AI
title VARCHAR(100) NOT NULL
child_id INT
parent_id INT

The child_id is used for the parent_id of the children (so you don't have to use a query to get the children if they're not exist).

Now, it kind of works. But if I add an item with the following data:

NULL
DELETEMELATER
0
2

I get a memory limit error:

<b>Fatal error</b>:  Allowed memory size of 536870912 bytes exhausted (tried to allocate 42 bytes)

Which is on this line:

return $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
950

Answer

Solution:

I guess your problem is with your dbstructure and itsdata as you have andparent_id andchild_id and if there will be an row which has and parent_id and child_id which are same you will have infinite loop of recursion and that is why you got out of memory exception, you have to fix your data in db or upgrate table strucvcure to have only parent_id and control your structure with it

Examples of infinite loop in your db structure case

1) item1 parent is item2 and item2 child is item1

2) if item2 is parent for item1 and item1 is parent for item3 but item3 is parent for item2

People are also looking for solutions to the problem: php - First element in a while loop?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.