Jump to content

Help sorting array


benphp

Recommended Posts

This is probably simple for someone. I want to sort an array but maintain the array index (0, 1, 2, etc). Here's my example:

 

<?php
$testy = array ();
$testy[] = "zebra";
$testy[] = "alligator";
$testy[] = "panda";
$testy[] = "kangaroo";
asort($testy);
for($K = 0; $K < sizeof($testy); $K++) { 
	$id = $K;
	print "ID = ".$K.";";
	print "Animal = ". $testy[$K];
	print "<br />";
}
?>

 

This sorts the array, but my index gets jacked. It displays:

 

ID = 0;Animal = zebra

ID = 1;Animal = alligator

ID = 2;Animal = panda

ID = 3;Animal = kangaroo

 

I want it to display:

 

ID = 3;Animal = zebra

ID = 0;Animal = alligator

ID = 3;Animal = panda

ID = 2;Animal = kangaroo

 

Help!

Link to comment
https://forums.phpfreaks.com/topic/147640-help-sorting-array/
Share on other sites

http://us3.php.net/manual/en/function.asort.php

 

edit: Tip for next time. If you know you are close, go to the PHP Doc for that function (in this case sort()), scroll down to See Also, and there is a list of similar functions and what the do. On the doc for sort, asort() is listed in the See Also as

asort() - Sort an array and maintain index association
Link to comment
https://forums.phpfreaks.com/topic/147640-help-sorting-array/#findComment-775051
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.