0

In one data I have a field title and field name ( field name is the name of a pdf file uploaded, for ex : My_file.pdf and title field is like an override for the front end, a null field)

I want to sort the data in alphabetical order taking into account the name field and the title field

Actually i tried to sort only by name like this :

                usort($filesContent, function($a, $b) {
                    return strcmp($a->getName(), $b->getName());
                });

But now I'm stuck, I don't see how to add a filter on the title

can someone guide me to solve my problem ? thanks

moho123
  • 35
  • 1
  • 8

2 Answers2

2

You callback function can do whatever you want. It only return value that matters. You need to return -1 when $a is "smaller" (whatever that means for you) than $b, 1 if $a is "greater" than $b or 0 if both are equal. So you basically with two sort keys, you sort by first and if you got 0 then you sort by second key.

usort($filesContent, function($a, $b) {
   $result = strcmp($a->getName(), $b->getName());
   return $result === 0
        ? strcmp($a->getTitle(), $b->getTitle())
        : $result;
});
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
2

You could concatenate both name and title into one string and compare... This would work for files with same filename but different titles. However this may have a weird effect with some data.

      usort($filesContent, function($a, $b) {
          return strcmp($a->getName().$a->getTitle(), $b->getName().$b->getTitle());
      });

You'd best sort by name first, then if the comparison is returning 0 meaning they are the same, sort by title.

      usort($filesContent, function($a, $b) {
          $nameSort = strcmp($a->getName(), $b->getName());
          if($nameSort == 0) return strcmp($a->getTitle(), $b->getTitle());
          return $nameSort;
      });
Salketer
  • 14,263
  • 2
  • 30
  • 58