* Sort a 2D array by a given column. * * @param array $data The input array of rows (each row is an array) * @param string $filterOptions All options * @return array The sorted array */
(array $data, string $filterOptions)
| 388 | * @return array The sorted array |
| 389 | */ |
| 390 | private function sortByColumn(array $data, string $filterOptions): array { |
| 391 | $filterOptions = json_decode($filterOptions, true); |
| 392 | if (!isset($filterOptions['sort'])) { |
| 393 | return $data; |
| 394 | } |
| 395 | |
| 396 | // Normalize direction |
| 397 | $direction = strtoupper($filterOptions['sort']['direction']); |
| 398 | $colIndex = $filterOptions['sort']['dimension']; |
| 399 | |
| 400 | usort($data, function (array $a, array $b) use ($colIndex, $direction) { |
| 401 | // If either row doesn't have that column, treat it as equal |
| 402 | if (!isset($a[$colIndex], $b[$colIndex])) { |
| 403 | return 0; |
| 404 | } |
| 405 | |
| 406 | // Compare using the spaceship operator (works for strings & numbers) |
| 407 | $cmp = $a[$colIndex] <=> $b[$colIndex]; |
| 408 | |
| 409 | // Flip for descending |
| 410 | return $direction === 'ASC' ? $cmp : -$cmp; |
| 411 | }); |
| 412 | |
| 413 | return $data; |
| 414 | } |
| 415 | |
| 416 | } |