I have the following array:
$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)']
How can I sort this array by the number in the brackets?
The result should look like that:
$anArray = ['someData (3)', 'anotherValue (5)', aValue (17)']
CodePudding user response:
This can solve your problem (its not the perfect way to do it)...
$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)'];
$keyValueArray = [];
$anArray = sortMyArray($anArray);
function sortMyArray($arr){
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;
}
CodePudding user response:
You can get the number using regex and pass that into the sort compare function, like this:
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.log($anArray);
CodePudding user response:
You can use regex to do this:
const $anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)'];
$anArray.sort((n1, n2) => {
return n1.match(/(\d )/)[0] - n2.match(/(\d )/)[0]
})
console.log($anArray)