0

I have a MySQL query that gets the result of the entire MySQL database into a php array called $parents

then I have a foreach function loop that display result from that array

the function:

 function subtree($id, $parents) { 
 if (isset($parents[$id]))
 foreach ($parents[$id] as $child) 
 {
 subtree($child, $parents);
 }
 } 

I need to sort the array result of this function, or to get the result into a new_sub_array then sort it and display result

any way to modify the function to do what i need?

user3117183
  • 49
  • 1
  • 1
  • 10

2 Answers2

0

Change your condition

if (is_array($parents[$id]))

If Value is array then look for next sub tree

else

otherwise write value.

If you want to sort an array - just use one of this function at the beginning of subtree()

Good idea is to don't use recursion, instead of this you can use iteration and well prepared sql query instead of sorting in PHP ;)

Your function could look like this, I am not sure if I understand you, but it should be ok.

function subtree($parents) 
{
    if (is_array($parents))
    {
        sort($parents);
        foreach ($parents as $key => $value) 
        {
            subtree($value);
        }
    }
    else
    {
        echo $parents;
    }
} 

The $id argument is unnecessary.

Michael
  • 1
  • 2
  • can you modify the function ? been trying that with no luck – user3117183 Dec 30 '13 at 22:34
  • the $id is the parent id that i need to get the child of. the array is like parent-LeftChild1,RightChild1 Parent(LeftChild1)-Leftchild2,RightChild2 ,, then the function should print each child of the main parents and childs of childs and so on, i just need to sort the result of the function – user3117183 Dec 30 '13 at 22:50
  • So if you want get child of specific parent id, then put to function as argument something like this $parent[$specific_id]. Did your array looks like this http://pastebin.com/JXdDRL5A ? – Michael Dec 30 '13 at 23:05
-1

You'd sort the values when you call them from the database. So if you sorted them in descending order of date, for example:

SELECT * FROM values WHERE :id=$id ORDER BY date DESC

Basically, ORDER BY is your friend. This helped me a lot.

CuriousCabbage
  • 414
  • 1
  • 5
  • 10