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
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;
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.