Re: Reshuffling an array

From: Date: Wed, 12 May 2004 18:22:12 +0000
Subject: Re: Reshuffling an array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-186032@lists.php.net to get a copy of this message
From: "Todd Cary" <todd@aristesoftware.com> > I do the following: > > $eventList = array(); > $eventList[] = "Any"; > $dbh = db_open($host, $user, $password, $database); > if($dbh) { > $sthdl = db_get_event_data($dbh); > while ($row = mysql_fetch_object($sthdl)) { > $eventList[] = $row->EV_EVENT; > } > } else { > $eventList[] = "* None found *"; > } > asort( $eventList ); > > Now I want to put "Any" as the first item. What is the best way to do > this? Often the sort puts it as an item down the list. Remove the line adding 'Any' at the beginning of your code and use array_unshift() to add it at the end. $eventList = array(); $dbh = db_open($host, $user, $password, $database); if($dbh) { $sthdl = db_get_event_data($dbh); while ($row = mysql_fetch_object($sthdl)) { $eventList[] = $row->EV_EVENT; } } else { $eventList[] = "* None found *"; } asort( $eventList ); array_unshift($eventList,'Any'); do you really need to maintain the numeric keys to the array by using asort() instead of just sort()? If so, this may not work. You may be able to use array_splice($input, 0, 0, array('Any')) or array_merge(). ---John Holmes...

« previous php.general (#186032) next »