Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort multi-dimensional, non-associative array on 2nd field

Status
Not open for further replies.

sen5241b

IS-IT--Management
Sep 27, 2007
199
US
I need to sort a multi-dimensional, non-associative array on the 2nd field. I read the data in from a simple CSV file. The first value is string and the second is a number. If there is no easy way to do this with a simple function, then is there a way to convert a non-associative array to an associative array so that I can sort an associative array using the function below?

Code:
// from php.net
function sortArrayByField( $original, $field, $descending = false )
        {
            $sortArr = array();
           
            foreach ( $original as $key => $value )
            {
                $sortArr[ $key ] = $value[ $field ];
            }
   
            if ( $descending )
            {
                arsort( $sortArr );
            }
            else
            {
                asort( $sortArr );
            }
           
            $resultArr = array();
            foreach ( $sortArr as $key => $value )
            {
                $resultArr[ $key ] = $original[ $key ];
            }
       
            return $resultArr;
        }
 
Its probably easier to use an associative array and this where cat is the second field:

Code:
usort($WordsArray, "cmp");
exit();

function cmp($a, $b)
{
    return strcmp($a["cat"], $b["cat"]);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top