* 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)
| 366 | * @return array The sorted array |
| 367 | */ |
| 368 | private function sortByColumn(array $data, string $filterOptions): array { |
| 369 | $filterOptions = json_decode($filterOptions, true); |
| 370 | if (!isset($filterOptions['sort'])) { |
| 371 | return $data; |
| 372 | } |
| 373 | |
| 374 | // Normalize direction |
| 375 | $direction = strtoupper($filterOptions['sort']['direction']); |
| 376 | $colIndex = $filterOptions['sort']['dimension']; |
| 377 | |
| 378 | usort($data, function (array $a, array $b) use ($colIndex, $direction) { |
| 379 | // If either row doesn't have that column, treat it as equal |
| 380 | if (!isset($a[$colIndex], $b[$colIndex])) { |
| 381 | return 0; |
| 382 | } |
| 383 | |
| 384 | // Compare using the spaceship operator (works for strings & numbers) |
| 385 | $cmp = $a[$colIndex] <=> $b[$colIndex]; |
| 386 | |
| 387 | // Flip for descending |
| 388 | return $direction === 'ASC' ? $cmp : -$cmp; |
| 389 | }); |
| 390 | |
| 391 | return $data; |
| 392 | } |
| 393 | |
| 394 | } |