Jump to content

Help Needed Sorting a 2D Array


MetroidMaster1914

Recommended Posts

I have an array that I've compiled, which, when printed, reads as:

Array
(
    [1] => Array
        (
            [file] => wallpaper1024.jpg
            [width] => 1024
            [height] => 768
        )

    [2] => Array
        (
            [file] => wallpaper800.jpg
            [width] => 800
            [height] => 600
        )

)

What I'm trying to do is sort it by the width from least to greatest, so that it results in:

Array
(
    [1] => Array
        (
            [file] => wallpaper800.jpg
            [width] => 800
            [height] => 600
        )

    [2] => Array
        (
            [file] => wallpaper1024.jpg
            [width] => 1024
            [height] => 768
        )

)

I know that there are a number of array sorting functions available, but I can't seem to figure out how to use them to sort this array like I need it to be. Can anyone help me out?

Link to comment
https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/
Share on other sites

Try this function

function sort_array($array, $key, $order)
{
if ($order=="DESC")
	$or="arsort";
else
	$or="asort";
for ($i = 0; $i < sizeof($array); $i++) 
{
	$sort_values[$i] = $array[$i][$key];
} 
$or($sort_values);
reset ($sort_values);
while (list ($arr_key, $arr_val) = each ($sort_values)) 
{
	$sorted_arr[] = $array[$arr_key];
}
return $sorted_arr;
}

 

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.