Это может решить вашу проблему
$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)'];
$anArray = sortMyArray($anArray);
function sortMyArray($arr){
$keyValueArray = [];
foreach ($arr as $element) {
// ( position
$start = strpos($element, '(');
// ) position
$end = strpos($element, ')', $start + 1);
$length = $end - $start;
// Get the number between parantheses
$num = substr($element, $start + 1, $length - 1);
// check if its a number
if (is_numeric($num)){
$keyValueArray[$num] = $element;
}
}
// Sort the array by its keys
ksort($keyValueArray);
// reassign your array with sorted elements
$arr = array_values($keyValueArray);
return $arr;
}
Вы можете получить число с помощью регулярного выражения и передать его в функцию сравнения сортировки, например:
function numerical(str) {
const pattern = /\(\d+\)/g;
const matches = str.match(pattern); // e.g. ["(25)"]
if (matches.length > 0) {
return parseInt(matches[0].slice(1, -1));
} else {
return 0;
}
}
$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)']
$anArray.sort((x,y) => numerical(x)-numerical(y));
console.info($anArray);
Вы можете использовать регулярное выражение для этого:
const $anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)'];
$anArray.sort((n1, n2) => {
return n1.match(/(\d+)/)[0] - n2.match(/(\d+)/)[0]
})
console.info($anArray)