* 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)
| 448 | * @return array The sorted array |
| 449 | */ |
| 450 | private function sortByColumn(array $data, string $filterOptions): array { |
| 451 | $filterOptions = json_decode($filterOptions, true); |
| 452 | if (!isset($filterOptions['sort'])) { |
| 453 | return $data; |
| 454 | } |
| 455 | |
| 456 | // Normalize direction |
| 457 | $direction = strtoupper($filterOptions['sort']['direction']); |
| 458 | $colIndex = $filterOptions['sort']['dimension']; |
| 459 | |
| 460 | usort($data, function (array $a, array $b) use ($colIndex, $direction) { |
| 461 | // If either row doesn't have that column, treat it as equal |
| 462 | if (!isset($a[$colIndex], $b[$colIndex])) { |
| 463 | return 0; |
| 464 | } |
| 465 | |
| 466 | // Compare using the spaceship operator (works for strings & numbers) |
| 467 | $cmp = $a[$colIndex] <=> $b[$colIndex]; |
| 468 | |
| 469 | // Flip for descending |
| 470 | return $direction === 'ASC' ? $cmp : -$cmp; |
| 471 | }); |
| 472 | |
| 473 | return $data; |
| 474 | } |
| 475 | |
| 476 | } |