Sort Array based on uniique value

I want to sort below array in descending order.
I want sorting based on value before .wav inside round bracket (xxx).
The value inside (xxx) will be unique.
(XXX) will be a unique 3 or 4 digit number.

Array (
 [0] => /records/
 [1] => /records/5000/[0xxxx822]_0xxx822-5xxx_20210324103339(366).wav
 [2] => /records/5xxx/[061xxx77]_0614xxxxx-5xxx_20210324104338(372).wav
 [3] => /records/5000/[08xxx3]_081xxxxx3-5xxx_20210324072915(299).wav
 [4] => /records/5xxx/[0xxx2xxx]_08xxxx5-5xxx_20210324085839(348).wav

In real scenario I will be having 1000 records.

To do this efficiently, you would index the data using the (xxx) values, then sort the data using that index.

If this is in a database table, you would create a column and populate it with the xxx values, then just sort on that column in a query.

If you must do this using php code, see this example -


$data = 
Array (
 1 => '/records/5000/[0xxxx822]_0xxx822-5xxx_20210324103339(366).wav',
 2 => '/records/5xxx/[061xxx77]_0614xxxxx-5xxx_20210324104338(372).wav',
 3 => '/records/5000/[08xxx3]_081xxxxx3-5xxx_20210324072915(299).wav',
 4 => '/records/5xxx/[0xxx2xxx]_08xxxx5-5xxx_20210324085839(348).wav',

// call-back function to index the data using the (xxx) value
function _index($element)
	// if you need complex pattern matching, use preg_match here, otherwise use simple, faster, string statements
	$start = strpos($element,'(');
	$end = strpos($element,')');
	$index = substr($element, $start+1, $end-$start-1);
	return [$index,$element];

// index the data
$data = array_map('_index',$data);

// function to dynamically build a usort sorter
function build_sorter($key, $direction = 'asc') {
    return function ($a, $b) use ($key, $direction) {
		if($direction == 'asc')
			return strnatcmp($a[$key], $b[$key]);
		} else {
			// anything other than 'asc' will sort descending
			return strnatcmp($b[$key], $a[$key]);

// usort using the 0th column, descending
usort($data, build_sorter(0,'desc'));

echo '<pre>'; print_r($data);
1 Like

It does work , I will edit more to get more accurate data. But you helped me 95% already.
Thank you.

Or, this would work, too.

// convert into indexed temp array
$temp_array = array();
foreach($input_array as $data) {
//  save each from the input array using the unique number as the index
$temp_array[ substr($data,-8,3) ] = $data;
ksort($temp_array);   //  Sort array by keys
//  Now the temporary array contains all the data sorted based on the (xxx) number.
Sponsor our Newsletter | Privacy Policy | Terms of Service