sorting array

Hi all,

May i know how to sort an array inside value, for example, a variable $record[] contain many sql output value (please see below structure)

$record[]=array(“carriername”=>$carrierarray,“countryid”=>$countryidarray,“pacd”=>$pacd);

now i wanted to sort by $pacd

i tried a function array_multisort($record[$pacd]);
but it is not working, how can do that?
Thanks

Brgds/Brandon Chau

Following example 3
http://no1.php.net/array_multisort#example-4968

I came up with this:

[php]<?php

$records = array(
0 => array(“carriername”=>‘carrier 1’,“countryid”=>‘country 1’,“pacd”=>‘nasfiasfj’),
1 => array(“carriername”=>‘carrier 2’,“countryid”=>‘country 2’,“pacd”=>‘ashjfaffs’),
2 => array(“carriername”=>‘carrier 3’,“countryid”=>‘country 2’,“pacd”=>‘asfasghff’),
3 => array(“carriername”=>‘carrier 4’,“countryid”=>‘country 2’,“pacd”=>‘yrtyrdydy’),
4 => array(“carriername”=>‘carrier 5’,“countryid”=>‘country 1’,“pacd”=>‘reyreytye’)
);

$pacd = array();
foreach ($records as $key => $record) {
$pacd[$key] = $record[‘pacd’];
}

array_multisort($pacd, SORT_ASC, $records);

echo ‘

’;
print_r($records);[/php]

[hr]

I would rather sort them in the query though. If you’re using mysql you should be able to just do a “ORDER BY pacd”

Sorting by query would be easier as JimL has already stated, but here’s a different spin on how to do the array way.

[php]<!doctype html>

Sorting Multidimensional Arrays <?php

$records = array(
0 => array(“carriername”=>‘carrier 1’,“countryid”=>‘country 1’,“pacd”=>‘nasfiasfj’),
1 => array(“carriername”=>‘carrier 2’,“countryid”=>‘country 2’,“pacd”=>‘ashjfaffs’),
2 => array(“carriername”=>‘carrier 3’,“countryid”=>‘country 2’,“pacd”=>‘asfasghff’),
3 => array(“carriername”=>‘carrier 4’,“countryid”=>‘country 2’,“pacd”=>‘yrtyrdydy’),
4 => array(“carriername”=>‘carrier 5’,“countryid”=>‘country 1’,“pacd”=>‘reyreytye’)
);

// Print the array as is:
echo ‘

Array As Is

’ . print_r($records, 1) . ‘
’;

function sort_by_pacd($x, $y) {
return strcasecmp($x[‘pacd’], $y[‘pacd’]);
}

uasort($records, ‘sort_by_pacd’);
echo ‘

Array Sorted by pacd

’ . print_r($records, 1) . ‘
’;

?>

[/php] ;)

Thanks JimL :slight_smile:

Hi Strider64 ,

The function works ;D

One more question , may i know how to control the sort Ascending and Descending order ? thanks :slight_smile:

Brgds/Brandon Chau

If I’m understanding you correctly all you have to do is switch the $x and the $y in the function to get it to descend or is that ascend…LOL :smiley: you get my drift.

Oh Yeah :smiley: :smiley:

Thank you Strider64 ^___________________^

Sponsor our Newsletter | Privacy Policy | Terms of Service