| | 3535 | * Sorts a list of objects, based on one or more orderby arguments. |
| | 3536 | * |
| | 3537 | * @since 4.6.0 |
| | 3538 | * |
| | 3539 | * @global array $_wp_list_sort |
| | 3540 | * |
| | 3541 | * @param array $list An array of objects to filter. |
| | 3542 | * @param string|array $orderby Optional. Either the field name to order by or an array |
| | 3543 | * of multiple orderby fields as $orderby => $order. |
| | 3544 | * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby |
| | 3545 | * is a string. |
| | 3546 | * @return array The sorted array. |
| | 3547 | */ |
| | 3548 | function wp_list_sort( $list, $orderby = array(), $order = 'ASC' ) { |
| | 3549 | if ( ! is_array( $list ) ) { |
| | 3550 | return array(); |
| | 3551 | } |
| | 3552 | |
| | 3553 | if ( empty( $orderby ) ) { |
| | 3554 | return $list; |
| | 3555 | } |
| | 3556 | |
| | 3557 | if ( is_string( $orderby ) ) { |
| | 3558 | $orderby = array( $orderby => $order ); |
| | 3559 | } |
| | 3560 | |
| | 3561 | foreach ( $orderby as $field => $direction ) { |
| | 3562 | $orderby[ $field ] = 'DESC' === strtoupper( $direction ) ? 'DESC' : 'ASC'; |
| | 3563 | } |
| | 3564 | |
| | 3565 | $GLOBALS['_wp_list_sort'] = $orderby; |
| | 3566 | |
| | 3567 | usort( $list, '_wp_list_sort_callback' ); |
| | 3568 | |
| | 3569 | unset( $GLOBALS['_wp_list_sort'] ); |
| | 3570 | |
| | 3571 | return $list; |
| | 3572 | } |
| | 3573 | |
| | 3574 | /** |
| | 3575 | * Callback function to sort a list of objects by specific fields. |
| | 3576 | * |
| | 3577 | * @since 4.6.0 |
| | 3578 | * @access private |
| | 3579 | * |
| | 3580 | * @see wp_list_sort() |
| | 3581 | * |
| | 3582 | * @global array $_wp_list_sort |
| | 3583 | * |
| | 3584 | * @param object|array $a One object to compare. |
| | 3585 | * @param object|array $b The other object to compare. |
| | 3586 | * @return int 0 if both objects equal. -1 if second object should come first, 1 otherwise. |
| | 3587 | */ |
| | 3588 | function _wp_list_sort_callback( $a, $b ) { |
| | 3589 | if ( ! isset( $GLOBALS['_wp_list_sort'] ) ) { |
| | 3590 | return 0; |
| | 3591 | } |
| | 3592 | |
| | 3593 | $a = (array) $a; |
| | 3594 | $b = (array) $b; |
| | 3595 | |
| | 3596 | foreach ( $GLOBALS['_wp_list_sort'] as $field => $direction ) { |
| | 3597 | if ( ! isset( $a[ $field ] ) || ! isset( $b[ $field ] ) ) { |
| | 3598 | continue; |
| | 3599 | } |
| | 3600 | |
| | 3601 | if ( $a[ $field ] == $b[ $field ] ) { |
| | 3602 | continue; |
| | 3603 | } |
| | 3604 | |
| | 3605 | $results = 'DESC' === $direction ? array( 1, -1 ) : array( -1, 1 ); |
| | 3606 | |
| | 3607 | if ( is_numeric( $a[ $field ] ) && is_numeric( $b[ $field ] ) ) { |
| | 3608 | return ( $a[ $field ] < $b[ $field ] ) ? $results[0] : $results[1]; |
| | 3609 | } |
| | 3610 | |
| | 3611 | return 0 > strcmp( $a[ $field ], $b[ $field ] ) ? $results[0] : $results[1]; |
| | 3612 | } |
| | 3613 | |
| | 3614 | return 0; |
| | 3615 | } |
| | 3616 | |
| | 3617 | /** |