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