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
https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/
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);

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

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.