Jump to content

Best way to sort this array...


Sulman

Recommended Posts

Hi all,

 

I have an array that i need to order but I'm looking for some advice as how to do it. The array looks like this:

<?php
$myarray[0]['order']  = 39;
$myarray[0]['title']  = "title 1";
$myarray[1]['order']  = 39;
$myarray[1]['title']  = "title 2";
$myarray[2]['order']  = 5;
$myarray[2]['title']  = "title 3";
$myarray[3]['order']  = 0;
$myarray[3]['title']  = "title 4";
etc...
?>

I need to be able to order the array in ascending order based on the "order" element so it will look like this:

<?php
$myarray[0]['order']  = 0;
$myarray[0]['title']  = "title 4";
$myarray[1]['order']  = 5;
$myarray[1]['title']  = "title 3";
$myarray[2]['order']  = 39;
$myarray[2]['title']  = "title 1";
$myarray[3]['order']  = 39;
$myarray[3]['title']  = "title 2";
etc...
?>

 

Any ideas how i would achieve this? Normally it would be pretty easy: simply use the order as the index of the array, but the problem with that is that I would lose one because there are two 39's!

 

Any clues?!

 

Thanks

Link to comment
Share on other sites

You need usort. Read about it.

 

function c ($a, $b) {
if (!array_key_exists('order', $a) || !array_key_exists('order', $b)) return 2;
if ($a['order'] == $b['order']) return strcmp($a['title'], $b['title']);
return $a['order'] < $b['order']? -1 : 1;
}

usort($myarray, 'c');
var_dump($myarray);

Link to comment
Share on other sites

array_multisort is the function for sorting multidimensional arrays

foreach ($myarray as $key => $row) {
    $count[$key]  = $row['count'];
array_multisort($count, SORT_ASC, $myarray);
print_r($myarray);
}

just replace$row['count'] with whatever you want sorted, in your case it would be $row['order'].

 

 

HTH

Teamatomic

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.