Reputation: 2358
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);
Upvotes: 3
Views: 601
Reputation: 4202
I guess your problem is with your db structure
and its data
as you have and parent_id
and child_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
Upvotes: 1