Two dimensional array sorting?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
AAO
Forum Newbie
Posts: 1
Joined: Fri Aug 12, 2005 7:28 am

Two dimensional array sorting?

Post by AAO »

Hello,

Well, I'm totally lost on sorting a 2-D array with string values. Here is the array named $filenames.


Array
(
[Ascii] => Array
(
[0] => ABC.htm
[1] => ACC.htm
)

[Hex] => Array
(
[0] => CAA.htm
[1] => AKA.htm
)

[Acs] => Array
(
[0] => CAA.htm
[1] => AKA.htm
)

I want to sort the array, first, outer array - so keys must be arranged like [Acs], [Ascii], and [Hex].

Then, I want to sort the inner array of each outer array without changing its association with the key.

How can I do this? I've tried several functions listed in php.net, but nothing has worked so far.

I really appreciate your help.

Regards,
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

multisort(), ksort(), uksort()
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

I tried this one before and wasn't successful. This works for me:

Code: Select all

<?php
$array = array(  'Ascii' => array( 'ABC.htm', 'ACC.htm', 'dog.htm','cat.htm', 'pig.htm'), 
				 'Hex' => array('CAA.htm', 'AKA.htm', 'foo.htm', 'bar.htm'), 
				 'Acs' => array ('CAA.htm', 'AKA.htm', 'car.htm', 'van.htm')); 

ksort($array);
reset($array);
//$r_array = array_map('sort', $array);
while (list( $k, $v) = each($array )){
	if (is_array($v)){
	   array_multisort ($v, SORT_STRING);
	   reset($v);
	}
}
print_r($array);
?>
Post Reply