chengkun
2025-09-12 26c5c0296e7c094f9a7ae4a4bb3c975796992eaf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
 
namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
 
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
 
class Filter
{
    public static function filter(array $lookupArray, mixed $matchArray, mixed $ifEmpty = null): mixed
    {
        if (!is_array($matchArray)) {
            return ExcelError::VALUE();
        }
 
        $matchArray = self::enumerateArrayKeys($matchArray);
 
        $result = (Matrix::isColumnVector($matchArray))
            ? self::filterByRow($lookupArray, $matchArray)
            : self::filterByColumn($lookupArray, $matchArray);
 
        if (empty($result)) {
            return $ifEmpty ?? ExcelError::CALC();
        }
 
        return array_values(array_map('array_values', $result));
    }
 
    private static function enumerateArrayKeys(array $sortArray): array
    {
        array_walk(
            $sortArray,
            function (&$columns): void {
                if (is_array($columns)) {
                    $columns = array_values($columns);
                }
            }
        );
 
        return array_values($sortArray);
    }
 
    private static function filterByRow(array $lookupArray, array $matchArray): array
    {
        $matchArray = array_values(array_column($matchArray, 0));
 
        return array_filter(
            array_values($lookupArray),
            fn ($index): bool => (bool) $matchArray[$index],
            ARRAY_FILTER_USE_KEY
        );
    }
 
    private static function filterByColumn(array $lookupArray, array $matchArray): array
    {
        $lookupArray = Matrix::transpose($lookupArray);
 
        if (count($matchArray) === 1) {
            $matchArray = array_pop($matchArray);
        }
 
        array_walk(
            $matchArray,
            function (&$value): void {
                $value = [$value];
            }
        );
 
        $result = self::filterByRow($lookupArray, $matchArray);
 
        return Matrix::transpose($result);
    }
}