Skip to content

Commit

Permalink
fixed sort array function for equal elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Fellan-91 committed May 14, 2024
1 parent 4313108 commit f1a2583
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions classes/class-get-portfolio.php
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,16 @@ private static function get_rand_seed_session() {
* @return array
*/
public static function sort_array_by_field( $array, $field, $order = 'desc' ) {
/**
* We add a service key to the properties of array elements to sort fields of equal value by keys.
* This is only necessary when sorting in descending order.
*/
if ( 'desc' === $order ) {
foreach ( $array as $key => &$element ) {
$element['service_key'] = $key;
}
}

usort(
$array,
function ( $a, $b ) use ( $field, $order ) {
Expand All @@ -1205,11 +1215,28 @@ function ( $a, $b ) use ( $field, $order ) {
return -1; // Place empty b fields at the end.
}

// Normal comparison.
return 'desc' === $order ? $b[ $field ] <=> $a[ $field ] : $a[ $field ] <=> $b[ $field ];
// Primary comparison by field values.
$comparsion = 'desc' === $order ? $b[ $field ] <=> $a[ $field ] : $a[ $field ] <=> $b[ $field ];
if ( 0 !== $comparsion ) {
return $comparsion;
}

// Secondary comparison by keys when values are equal.
if ( 'desc' === $order ) {
return $b['service_key'] <=> $a['service_key']; // Replace 'service_key' with the actual key field name.
}

return 0; // No secondary sorting needed for ascending order or equal values.
}
);

// Clearing the array of service keys.
if ( 'desc' === $order ) {
foreach ( $array as $key => &$element ) {
unset( $element['service_key'] );
}
}

return $array;
}

Expand Down

0 comments on commit f1a2583

Please sign in to comment.