phpusort

How to sort array by substring? (¨PHP)


I have created method to sort array with values like this: array('regdate','birthday','editdate') which should sort the elements in the way that the elements containing word date should be moved to left like this array('regdate','editdate','birthday')

public function sortColumnsBySubstring($haystack, $substr){
   if ($haystack == $substr) {
          return 0;
      }
    return strpos($substr) !== false ? -1 : 1; 
 }

However it is not clear to me how to make this working. Example which I have found in php manual shows function with no arguments or closures - I use php version 5.2 so I cannot use closures.

All I can think up is this usort($date_cols, $this->sortColumnsBySubstring($value, 'date') but here $value is undefined so it's not solution.

Question is how to implement the function to work correctly?


Solution

  • First solution is to my original question:

    function cmp($a, $b)
    {
        $adate = (strpos($a, 'date') !== false);
        $bdate = (strpos($b, 'date') !== false);
        if (!($adate ^ $bdate)) return strcmp($a, $b);
        return $adate ? -1 : 1;
    }
    
    $a = array('birthday', 'regdate', 'editdate');
    usort($a, 'cmp');
    

    Second solution uses splitting into two arrays, sort and then merge them back. I have tried to use more word related to time to identify the values related to time.

     private function getDateColumns(&$array)
     {
     $search_date_columns = array('date','datetime','timestamp','time','edited','changed','modified','created','datum');
     $result = array( array(), array() );
     foreach($array as $v1):
      $found = false;
      foreach($search_date_columns as $v2)
        if ( strpos($v1, $v2)!==false )
          { $found = true; break; }
      if ($found)
        $result[0][] = $v1;
      else
        $result[1][] = $v1;
     endforeach;
     return $result;
     }
    

    Which is implemented like that:

    $date_cols = array('regdate','time','editdate','createdate','personal','mojedatum','edited','test','modified','changed','pokus','timestamp','hlava');
    $arrays = $this->getDateColumns($date_cols);
    rsort($arrays[0]);
    $date_cols = array_merge($arrays[0], $arrays[1]); 
    unset($arrays);
    print_r($date_cols);