Jump to content

Sorting...


springo

Recommended Posts

Hi,

I was trying to sort a multi-dimensional array with one dimension being the sorting criteria.

I wanted to make it sort by an alternative one if the main one is equal on two entries.

However that doesn't work: it sorts properly according to the main criteria, but it won't sort according to the alternative one.

I hope you understood what I'm trying to say, since I'm not a native English speaker.

 

Here is my code:

<?php
# $sort = sort criteria
# $alter_sort = alternative sort criteria
# $order = true if descending; false if ascending

function sort_data($a, $b)
{
  global $sort,$alter_sort,$order;
  if ($a[$sort] == $b[$sort]) {
    if ($a[$alter_sort] == $b[$alter_sort])
      return 0;
return ((intval($a[$alter_sort]) < intval($b[$alter_sort])) && $order) ? 1 : -1;
  }
  return ((intval($a[$sort]) < intval($b[$sort])) && $order) ? 1 : -1;
}

function resort()
{
  global $data;
  usort($data, "sort_data");
}
?>

Thank you very much for your help!

Link to comment
https://forums.phpfreaks.com/topic/46063-sorting/
Share on other sites

OK, let's see:

$my_array [0] [$sort] = "103"
              [$alter_sort] = "67"
          [1] [$sort] = "75"
              [$alter_sort] = "98"
          [2] [$sort] = "103"
              [$alter_sort] = "77"

And I'd want to sort that to ($order = true):

$my_array [0] [$sort] = "103"
              [$alter_sort] = "77"
          [1] [$sort] = "103"
              [$alter_sort] = "67"
          [2] [$sort] = "75"
              [$alter_sort] = "98"

But I'm getting ($order = true):

$my_array [0] [$sort] = "103"
              [$alter_sort] = "67"
          [1] [$sort] = "103"
              [$alter_sort] = "77"
          [2] [$sort] = "75"
              [$alter_sort] = "98"

Link to comment
https://forums.phpfreaks.com/topic/46063-sorting/#findComment-223827
Share on other sites

<?php
$my_array [0] ['sort'] = "103" ;
$my_array [0] ['alter_sort'] = "67";
$my_array [1] ['sort'] = "75";
$my_array [1] ['alter_sort'] = "98";
$my_array [2] ['sort'] = "103";
$my_array [2] ['alter_sort'] = "77" ;

function mysort($a, $b)
{
    if ($a['sort']==$b['sort']) {
        if ($a['alter_sort']==$b['alter_sort']) return 0;
        return (intval($a['alter_sort']) < intval($b['alter_sort'])) ? 1 : -1;
    }
    return (intval($a['sort']) < intval($b['sort'])) ? 1 : -1; 
}


echo '<pre> Original ', print_r($my_array, true), '</pre>';

usort($my_array, 'mysort');

echo '<pre> Sorted ', print_r($my_array, true), '</pre>';
?>

Link to comment
https://forums.phpfreaks.com/topic/46063-sorting/#findComment-223855
Share on other sites

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.