0

Here is my Multi Sort Code.

But, How can i do this for individual coloumns

What i have done so far is

PHP Code :

<?php
$a1=array("Cat","Alpha","two");
$a1=array("Cat","Beta","two");
$a1=array("Pluto","Beta","two");
$a1=array("Pluto","Alpha","two");
array_multisort($a1[0], SORT_ASC, SORT_STRING, $a1[1], SORT_NUMERIC, SORT_DESC);
$json[] = $a1;
$final=array("response"=>$a1);
echo json_encode($final);
?>

It will display as

Array ( [0] => Cat [1] => Dog [2] => zb ) Array ( [0] => Missy [1] => Pluto [2] => Fido )

But , I want to display the

First Coloumn of $a1 as Asc, then Second Coloumn of $a1 as Desc,

So that the result should be

Col A  Col B, Col C
Cat,   Alpha  two
Cat,   Beta   two
Pluto, Alpha  two
Plugo, Beta   two

How can i do this ?

SA__
  • 1,330
  • 2
  • 15
  • 36
  • 1
    Make a more useful array structure, like `array(array('type' => 'Dog', 'name' => 'Pluto'), ...)`, then see http://stackoverflow.com/q/17364127/476. – deceze Sep 30 '14 at 11:10
  • Thanks for the link , but there in the array_multisort i can't find enough workout :( – SA__ Sep 30 '14 at 11:51

2 Answers2

1

I guess you want to use usort to build your own custom sorting algorithm:

<?php
$array = array(
    array("Cat","Alpha","two"),
    array("Cat","Beta","two"),
    array("Pluto","Beta","two"),
    array("Pluto","Alpha","two"),
);

function my_custom_sort($a, $b)
{
    // first sort ASC by first column
    if ($a[0] == $b[0]) {
        // then sort ASC by second column
        if ($a[1] == $b[1]) {
            return 0;
        } else {
            return $a[1] < $b[1] ? -1 : 1;
        }
    } else {
        return $a[0] < $b[0] ? -1 : 1;
    }
}

usort($array, 'my_custom_sort');
var_dump($array);
winkbrace
  • 2,525
  • 22
  • 19
0
<?php
$a1=array("Dog","zb","Cat");
$a2=array("Pluto","Fido","Missy");

array_multisort($a1,SORT_ASC);
array_multisort($a2,SORT_DESC);
print_r($a1);
print_r($a2);
?>
Ankur Bhadania
  • 3,954
  • 1
  • 22
  • 34