Need a better, less memory intensive way to organize an unnested parent->child array
I've been using a function I made when I first started programming (Or shortly thereafter at least) to do the simple but extremely useful task of organizing an array based on parents and children. An example of where this would be useful would be for, say, if you had a list of items that can have an infinite depth of children in a database, and you need to present the list in order in an html select elemen开发者_如何学JAVAt with a visual representation (--) of depth for each child.
Now, I have the function(s) that do this, and they work under all the situations that I've put them in, however they clone the array countless times... So far this hasn't been an issue, but I'm starting to use this function in places that could have tens of thousands of entries it needs to organize. So I'm hoping someone here could help me optimize it.
The code: http://pastebin.com/knk0Fyd0
Take the count()
function out of the loop. It's a bottleneck. Instead of:
for ($i=0;$i<count($array);$i++)
Use this:
$count=count($array);
for ($i=0;$i<$count;$i++)
Your InsertAfter()
function could have been easily accomplished with PHP's array_splice()
and/or array_slice()
.
精彩评论