Jump to content

Sort Array by 2nd Index


xProteuSx

Recommended Posts

I've got a multidimensional array that has 2 columns.  The first column is numerical (country_id), and the second column is text (country_name), which may or may not be data that will be turned into an array. 

 

Looks something like this:

 

column 1 (index 0) = 42

column 2 (index 1) = Great Britain|England

 

I use a while loop to create an array of these rows, then a use a foreach loop to go through index[1] of each row.  If there is a single name for a country, it is added to a new array, but if there is more than one name for a country, then both names are added to the new array. So, for example, if we had this data:

 

row1

column 1 (index 0) = 12

column 2 (index 1) = Algeria

 

row2

column 1 (index 0) = 22

column 2 (index 1) = Ethiopia

 

row3

column 1 (index 0) =42

column 2 (index 1) = Great Britain|England

 

Then the final array would look like this:

 

index[0] = 12  index[1] = Algeria

index[0] = 22  index[1] = Ethiopia

index[0] = 42  index[1] = Great Britain

index[0] = 42  index[1] = England

 

Now I would like to sort by index[1] to get the following alphabetical order:

 

index[0] = 12  index[1] = Algeria

index[0] = 42  index[1] = England

index[0] = 22  index[1] = Ethiopia

index[0] = 42  index[1] = Great Britain

 

What do I use?  I've fooled around with sort, usort, asort ... can't figure it out.

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/253300-sort-array-by-2nd-index/
Share on other sites

Got this tidbit from the PHP website:

 

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE)

            {

        if(is_array($array) && count($array)>0)

                {

            foreach(array_keys($array) as $key)

            $temp[$key]=$array[$key][$index];

            if(!$natsort)

                    {

                if ($order=='asc')

                    asort($temp);

                else 

                    arsort($temp);

            }

            else

            {

                if ($case_sensitive===true)

                    natsort($temp);

                else

                    natcasesort($temp);

            if($order!='asc')

                $temp=array_reverse($temp,TRUE);

            }

            foreach(array_keys($temp) as $key)

                if (is_numeric($key))

                    $sorted[]=$array[$key];

                else 

                    $sorted[$key]=$array[$key];

            return $sorted;

        }

    return $sorted;

}

               

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.