Search code examples
phpsortingglob

How can I sort PHP globs by a variable within its elements?


I have a glob of files within a certain directory. These files are PHP files with variable definitions. In these files are a custom 'date' variable. These dates do not match up with when the PHP file was created, but rather an otherwise arbitrary date. I am unsure of how to sort the glob based on those variables.

So far I have been unable to create a successful compare function or use ksort or similar functions to sort the glob based on variables within it.

The content of a standard item found by the glob will appear like this:

<?php
$title = 'Example Title';
$info = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
$time = mktime(22,19,46,10,14,2019); //THIS IS WHAT I WOULD LIKE TO SORT BY
$datestring = date("d F, Y H:i",$time);
?>

I would assume I should be able to sort given a variable from each element of the glob (for example the 'time' variable of each file in the glob) but I have been unable to find a sort function to allow this. Any sort I have found have sorted keys within an array, but these files are not arrays themselves so they have been incompatible.


Solution

  • You need the $time variable from each file. You must therefore include every file in the loop with include, include_once is wrong here.

    $files = glob("yourpath/*.php");
    $array = array();
    foreach($files as $file){
      include $file;
      $array[$time] = $file;
    }
    ksort($array);
    

    Note:

    This simple variant with ksort only works if different $time information is in each file.

    Maybe it's better

    $files = glob("yourpath/*.php");
    $array = array();
    foreach($files as $key => $file){
      include $file;
      $array[$file] = $time;
    }
    asort($array);