Memory leak in recursive function with reference

I got the following code. This is a system for receiving items and all children children children children ... subject. Well, I use a recursive function for this:

<?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 table of elements is as follows:

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

Child_id is used for parent_id for children (so you do not need to use a query to get children if they do not exist).

Now it works. But if I add an element 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)

What is in this line:

return $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
+4
source share
1 answer

, db structure data, , parent_id child_id, , parent_id child_id, , , , db strucvcure, parent_id

db

1) item1 - item2, item2 - item1

2), item2 item1, item1 item3, item3 item2

+2

Source: https://habr.com/ru/post/1619328/


All Articles