Categories > TinyButStrong general >

How can I sort this type of aray by telling witch key I'll sort on (asc/Desc)

The forum is closed. Please use Stack Overflow for submitting new questions. Use tags: tinybutstrong , opentbs
By: Webys
Date: 2005-04-14
Time: 16:55

How can I sort this type of aray by telling witch key I'll sort on (asc/Desc)

If I wish to sort by name key or by city key ascendent or descendent how can I do it?

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Matias  Brown
            [city] => Los Angeles

        )
    [1] => Array
        (
            [id] => 2
            [name] => Andy Falco
            [city] => Las Vegas

        )

    [2] => Array
        (
            [id] => 3
            [name] => Brian Garvin
            [city] => San Francisco

        )
}


Thanks.
By: Skrol29
Date: 2005-04-15
Time: 10:50

Re: How can I sort this type of aray by telling witch key I'll sort on (asc/Desc)

Hi,

TBS cannot do that for you. And Php sorting functions sort only value, not sub-values. You have to use a sort algorithm. A good one and simple to code is the bubble sort algorithm.
An example here:
http://www.metalshell.com/view/source/118/
By: Webys
Date: 2005-04-18
Time: 10:52

Re: How can I sort this type of aray by telling witch key I'll sort on (asc/Desc)

Thanks Skrol29, I've made my own function for that...If someone needs an multy array sort function by keys here it is:

function arr_keys_multisort($arr,$my_key,$sort_type)
{

  foreach ($arr as $key => $row) {
     $arr_tmp[$key]  = $row["$my_key"];

  }

  if ($sort_type=='desc') array_multisort($arr_tmp, SORT_DESC, $arr);
  else  array_multisort($arr_tmp, SORT_ASC, $arr);

  return $arr;
}