Fatal error: Allowed memory size of 536870912 bytes exhausted

I have the following function that runs well when executed in view of Yii;




function formatTree($tree, $parent){

    $tree2 = array();

    foreach($tree as $i => $item)

    {

        if($item['parent'] == $parent)

        {

            $tree2[$item['id_produto_categoria']] = $item;

            $tree2[$item['id_produto_categoria']]['submenu'] = formatTree($tree, $item['id_produto_categoria']);

        }

    }

    return $tree2;

}



The problem started when I wrote the above function in the model, to better separate the codes, did so; (model)

Error: Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 261900 bytes) in C:\Apache2.2\htdocs\yiiadministracao\protected\modules\administracao\models\ProdutosCategorias.php on line 71




        public function getCategoriasFormatted($value, $parent)

        {

            $tree2 = array();

            foreach($value as $i => $item)

            {

                if($item['parent'] == 0)

                {

                    $tree2[$item['id_produto_categoria']] = $item;

                    (LINE 71) $tree2[$item['id_produto_categoria']]['submenu'] = $this->getCategoriasFormatted($value, $item['id_produto_categoria']);

                }

            }

            return $tree2;            

        }



Can anyone help?

Allowed memory size of 536870912 bytes exhausted

That is sometime i meant b4.

the above code may be or may not reflect the problem cause above memory allocate exhausted,

in my case, make a breakpoint that yrs main class/es causing error, use independent unit test that find out why it allocate so more memory, by using loop? by allocate class memory?, by new (not assign) so much duplicate var that useless or just little work?

that is my past solution. Debug is time consuming, refactoring should be need.

Maicon,

Is your name as a famous football player?

About your code, I think that because your data were wrong, not your code. Some categories inherited from their children, it made a cycle recursive inheration. Just check your data first.

Or you may want to try my code, it’s a bit of magically with variable references.




public function getCategoriasFormatted($value)

{

	$tree = array();

	$ref = array();

	foreach ($value as $i=>&$e) {

		$e['submenu'] = array();

		$ref[$e['id_produto_categoria']] = & $e;

	}

	unset ($e);


	foreach($value as $i => &$e)

	{

		$eId = $e['id_produto_categoria'];

		$eParentId = $e['parent'];


		if(empty($eParentId)) $tree[$eId] = &$e;

		elseif (isset($ref[$eParentId])) $ref[$eParentId]['submenu'][] = & $e;

		else assert(false); # if you get here, your data were wrong

	}


	return $tree;

}

Happy weekend,

Thanks everyone for answers, but found the error in the code, a primary error!




if($item['parent'] == 0)

{



correction




if($item['parent'] == $parent)

{