PHP Multidimentional Array sort

Posted on January 2, 2008. Filed under: php |

Ok friends , as promised i will be sharing my knowledge of php with you , in this series , here is my first script for you

This a very simple function on how to sort a multidimentional array in php

function sort_multi_array($mult_array , $field , $sort_type="ASC_NUM")
{

$code = '';
switch($sort_type) {

case ASC_NUM:
$code .= 'return strcmp($a["'.$field.'"], $b["'.$field.'"]);';
break;
case DESC_NUM:
$code .= 'return (-1*strcmp($a["'.$field.'"], $b["'.$field.'"]));';
break;
}

$compare = create_function('$a, $b', $code);
usort($mult_array, $compare);
return $mult_array;
}

//How to use :
$data[] = array('volume' => 67, 'date' => '2008-12-30 21:20:56', 'name' => "abc");
$data[] = array('volume' => 86, 'date' => '2007-12-25 21:20:56', 'name' =>'def' );
$data[] = array('volume' => 85, 'date' => '2007-12-27 21:20:56', 'name' => 'ghi');
$data[] = array('volume' => 05, 'date' => '2008-12-02 21:20:56', 'name' => 'jkl');
$data[] = array('volume' => 86, 'date' => '1975-12-05 21:20:56', 'name' => 'mno');
$data[] = array('volume' => 67, 'date' => '2007-12-30 20:20:56', 'name' => 'rto');

$data = sort_multi_array($data ,'date' , 'DESC_NUM');
var_dump($data);

/*

it will sort the array according to 'date'

array(6) {
[0]=>
array(3) {
["volume"]=>
int(67)
["date"]=>
string(19) "2008-12-30 21:20:56"
["name"]=>
string(3) "abc"
}
[1]=>
array(3) {
["volume"]=>
int(5)
["date"]=>
string(19) "2008-12-02 21:20:56"
["name"]=>
string(3) "jkl"
}
[2]=>
array(3) {
["volume"]=>
int(67)
["date"]=>
string(19) "2007-12-30 20:20:56"
["name"]=>
string(3) "rto"
}
[3]=>
array(3) {
["volume"]=>
int(85)
["date"]=>
string(19) "2007-12-27 21:20:56"
["name"]=>
string(3) "ghi"
}
[4]=>
array(3) {
["volume"]=>
int(86)
["date"]=>
string(19) "2007-12-25 21:20:56"
["name"]=>
string(3) "def"
}
[5]=>
array(3) {
["volume"]=>
int(86)
["date"]=>
string(19) "1975-12-05 21:20:56"
["name"]=>
string(3) "mno"
}
}

/*

Advertisements

Make a Comment

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

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: