Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
   1  <?php
   2  
   3  namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
   4  
   5  use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
   6  
   7  class Filter
   8  {
   9      /**
  10       * @param mixed $lookupArray
  11       * @param mixed $matchArray
  12       * @param mixed $ifEmpty
  13       *
  14       * @return mixed
  15       */
  16      public static function filter($lookupArray, $matchArray, $ifEmpty = null)
  17      {
  18          if (!is_array($matchArray)) {
  19              return ExcelError::VALUE();
  20          }
  21  
  22          $matchArray = self::enumerateArrayKeys($matchArray);
  23  
  24          $result = (Matrix::isColumnVector($matchArray))
  25              ? self::filterByRow($lookupArray, $matchArray)
  26              : self::filterByColumn($lookupArray, $matchArray);
  27  
  28          if (empty($result)) {
  29              return $ifEmpty ?? ExcelError::CALC();
  30          }
  31  
  32          return array_values(array_map('array_values', $result));
  33      }
  34  
  35      private static function enumerateArrayKeys(array $sortArray): array
  36      {
  37          array_walk(
  38              $sortArray,
  39              function (&$columns): void {
  40                  if (is_array($columns)) {
  41                      $columns = array_values($columns);
  42                  }
  43              }
  44          );
  45  
  46          return array_values($sortArray);
  47      }
  48  
  49      private static function filterByRow(array $lookupArray, array $matchArray): array
  50      {
  51          $matchArray = array_values(array_column($matchArray, 0));
  52  
  53          return array_filter(
  54              array_values($lookupArray),
  55              function ($index) use ($matchArray): bool {
  56                  return (bool) $matchArray[$index];
  57              },
  58              ARRAY_FILTER_USE_KEY
  59          );
  60      }
  61  
  62      private static function filterByColumn(array $lookupArray, array $matchArray): array
  63      {
  64          $lookupArray = Matrix::transpose($lookupArray);
  65  
  66          if (count($matchArray) === 1) {
  67              $matchArray = array_pop($matchArray);
  68          }
  69  
  70          array_walk(
  71              $matchArray,
  72              function (&$value): void {
  73                  $value = [$value];
  74              }
  75          );
  76  
  77          $result = self::filterByRow($lookupArray, $matchArray);
  78  
  79          return Matrix::transpose($result);
  80      }
  81  }