[thelist] Multidimensional Array sort

J.J.SOLARI jjsolari at pobox.com
Thu Mar 11 08:34:34 CST 2004


> Date: Wed, 10 Mar 2004 16:25:03 -0400

    [...]
     

> but if I change the 'inner' array from numbers to "words", then it
does 
> not:
> 
> Array
> (
>      [0] => Array
>          (
>              [Callsign] => EJM10
>              [Sort] => EJM10
>              [ID] => 23
>              [Type] => C550
>          )
> 
>      [1] => Array
>          (
>              [Callsign] => EJM1
>              [Sort] => EJM1
>              [ID] => 11
>              [Type] => A550
>          )

    [...]
    
> I have tried :-array_multisort($ar[1], $ar[0], ar[2], $ar[3]), but it 
> doesn't sort.
> I have tried :-array_multisort($ar["Sort"], $ar["Callsign"], ar["ID"], 
> $ar["Type"]), but I get the following message:
> Warning: Argument 1 to array_multisort() is expected to be an array or
a 
> sort flag
> 
> Any advice would be really appreciated.
> 
> BTW, I am trying to sort on the the 'Sort' field and would like a 
> Natural sort.

Alexis,

Look on php.net, in the user comments for the function array_multisort,
<http://fr3.php.net/manual/en/function.array-multisort.php>

There is a beautiful function named 'array_csort', coded by Ichier, that
reproduce the ORDER BY instruction of SQL.

The structure of your array needs to be:

$arrayUnsorted = array(
    array(
        "Sort" => "valsort1",
        "Callsign" => "valcallsign1",
        "Id" => "valid1",
        "Type" => "valType1" ),
    array(
        "Sort" => "valsort2",
        "Callsign" => "valcallsign2",
        "Id" => "valid2",
        "Type" => "valType2" ),
    array( etc. )
    ...
    );

Then, for example, you would sort your array by "Sort" like this:

$arraySorted = array_csort( $arrayUnsorted, "Sort", "Callsign", "Id",
"Type" );

Note that you just need to order your array keys by sorting order
priority (here you sort by "Sort" :-). Else, you can specify sort_flags
which apply to the preceding key.

For example, you could do:
array_csort( $arrayUnsorted, "Sort", SORT_DESC, SORT_STRING, "Callsign",
"ID", "Type") for descending sort and all values treated as strings.

Really nice function,

hih,

JJS.


More information about the thelist mailing list