Page 1 of 1

Sorting an Array

Posted: Fri Feb 11, 2011 8:09 am
by cemiluyanik
I am trying to sort the following array

Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 41 )
[1] => Array ( [0] => 463 [1] => 465 [2] => 487 )
[2] => Array ( [0] => 463 [1] => 464 [2] => 477 )
[3] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 43 )
[4] => Array ( [0] => 463 [1] => 465 [2] => 488 )
)

as the one below. (Please see # of keys differences between 1 and 2)

Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 41 )
[1] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 43 )
[2] => Array ( [0] => 463 [1] => 464 [2] => 477 )
[3] => Array ( [0] => 463 [1] => 465 [2] => 487 )
[4] => Array ( [0] => 463 [1] => 465 [2] => 488 )
)

Is there a function or solution that I can use to accomplish this task? Anybody can help?

Re: Sorting an Array

Posted: Fri Feb 11, 2011 8:55 am
by anantha
what is the logic behind this change from one array to another..if you can say that, then i can think about is there a function already their in php...

Re: Sorting an Array

Posted: Fri Feb 11, 2011 9:02 am
by cemiluyanik
The idea is to create a tree view from a parent-child relation table. For example:

category 1
item 1
item 2
item 3

category 2
subcategory 1
item 1

i have all the items in a table. id, title, parentid
if no parent, parentid is null. I query the database, pull the items, put them in an array and now need to sort the array so that I can call them one by one to place them correctly. I tried to use the sort fuction but it does not help so much since the array different number of levels in depth. Hope this helps.

Re: Sorting an Array

Posted: Fri Feb 11, 2011 5:01 pm
by LuaMadman
Not sure, but think this will do the trick for you.

Code: Select all

	foreach ($array as $key => $row) { // loop our array
		$m[$key] = $row[0]; // get value of key 0 in subarray, and insert in to m
	}
	array_multisort($array,SORT_ASC,$m);

Re: Sorting an Array

Posted: Mon Feb 14, 2011 8:24 am
by zuu2343
Thank you!!!!!
This is the end result I received so far. This gave me a great start though, I will work on this and post if I am able to sort it through.
Again, thank you for your time and effort on this.

Array ( [0] =>
Array ( [0] => 463 [1] => 464 [2] => 474 )
[1] => Array ( [0] => 463 [1] => 464 [2] => 477 )
[2] => Array ( [0] => 463 [1] => 465 [2] => 487 )
[3] => Array ( [0] => 463 [1] => 465 [2] => 488 )
[4] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 41 )
[5] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 42 )
[6] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 43 )
[7] => Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 44 )
)