PHP natsort (Natural Sort) MultiDimension Array popped with Mysql Data

Hi Guys

Don’t ask me how I did that, but this method is working fine for me. We often have problems in sorting the multidimension array in natural way. This includes when we sort list of postcodes. ForExample I have a list of postcodes in my database and when I sort them ASC they appear as

AB1
AB10
AB12
AB2
AB21
AB22

This is not ideal as we want AB1, AB2, AB10, AB12, AB21

SO I wrote this piece of code to sort my data

$records=$this->postcodes_list;	


$keys = array();
$values = array();
$keys[]='0';


foreach ($records as $index => $row) {
//   $key = $row->postcode_s.'__'.$index; // Add the index to create an unique key.
   $key = $row->postcode_s; ////postcode_s is the column name which contains the postcodes
   $keys[] = $key;
   $values[$key] = $row; 
}

natsort($keys);///this method naturally sort the keys
$sortedValues = array();
foreach($keys as $index) {
  $sortedValues[] = $values[$index]; 
}


/*foreach ($sortedValues as $i=>$a){
	echo "Postcode : $a, Index: $i 
"; } */ foreach ($keys as $i=>$a){ echo "Postcode : $a, Index: $i
"; }

$records=$this->postcodes_list; ///Contains the list of postcodes

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s