Advertisement
Guest User

123

a guest
Feb 15th, 2021
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. die( '-1' );
  4. }
  5.  
  6. /**
  7. * Sort array values by key, default key is 'weight'
  8. * Used in uasort() function.
  9. * For fix equal weight problem used $this->data array_search
  10. *
  11. * @since 4.4
  12. */
  13.  
  14. /**
  15. * Class Vc_Sort
  16. * @since 4.4
  17. */
  18. class Vc_Sort {
  19. /**
  20. * @since 4.4
  21. * @var array $data - sorting data
  22. */
  23. protected $data = array();
  24. /**
  25. * @since 4.4
  26. * @var string $key - key for search
  27. */
  28. protected $key = 'weight';
  29.  
  30. /**
  31. * @param $data - array to sort
  32. * @since 4.4
  33. *
  34. */
  35. public function __construct( $data ) {
  36. $this->data = $data;
  37. }
  38.  
  39. /**
  40. * Used to change/set data to sort
  41. *
  42. * @param $data
  43. * @since 4.5
  44. *
  45. */
  46. public function setData( $data ) {
  47. $this->data = $data;
  48. }
  49.  
  50. /**
  51. * Sort $this->data by user key, used in class-vc-mapper.
  52. * If keys are equals it SAVES a position in array (index).
  53. *
  54. * @param string $key
  55. *
  56. * @return array - sorted array
  57. * @since 4.4
  58. *
  59. */
  60. public function sortByKey( $key = 'weight' ) {
  61. $this->key = $key;
  62. uasort( $this->data, array(
  63. $this,
  64. 'key',
  65. ) );
  66.  
  67. return array_merge( $this->data ); // reset array keys to 0..N
  68. }
  69.  
  70. /**
  71. * Sorting by key callable for usort function
  72. * @param $a - compare value
  73. * @param $b - compare value
  74. *
  75. * @return int
  76. * @since 4.4
  77. *
  78. */
  79. private function key( $a, $b ) {
  80. $a_weight = isset( $a[ $this->key ] ) ? (int) $a[ $this->key ] : 0;
  81. $b_weight = isset( $b[ $this->key ] ) ? (int) $b[ $this->key ] : 0;
  82. // To save real-ordering
  83. if ( $a_weight === $b_weight ) {
  84. // @codingStandardsIgnoreLine
  85. $cmp_a = array_search( $a, $this->data );
  86. // @codingStandardsIgnoreLine
  87. $cmp_b = array_search( $b, $this->data );
  88.  
  89. return $cmp_a - $cmp_b;
  90. }
  91.  
  92. return $b_weight - $a_weight;
  93. }
  94.  
  95. /**
  96. * @return array - sorting data
  97. * @since 4.4
  98. *
  99. */
  100. public function getData() {
  101. return $this->data;
  102. }
  103. }
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement