I have a php array $data which contains a list of files
[3945] => 6358--338940.txt
[3946] => 6357--348639.txt
[3947] => 6356--348265.txt
[3948] => 6354--345445.txt
[3949] => 6354--340195.txt
I need to order the array using the the numeric value after -- in the filename. How to do that ?
Thanks Regards
If you want an algorithm, the good way could be to :
explode()
function (http://php.net/manual/en/function.explode.php) and populate your temporary arrayintval()
function (http://php.net/manual/fr/function.intval.php) while populatingsort()
functionHere is the code to do so :
<?php
/* your code here */
$tempArray = [];
foreach ($d as $data) {
$value = explode("--", $d);
$value = $value[1]; // Take the chain "12345.txt"
$value = explode(".", $value);
$value = $value[0]; // Take the chain "12345"
$value = intval($value); // convert into integer
array_push($tempArray, $value);
}
sort($value);
?>
Your best choice is to use uasort.
>>> $data
=> [
3945 => "6358--338940.txt",
3946 => "6357--348639.txt",
3947 => "6356--348265.txt",
3948 => "6354--345445.txt",
3949 => "6354--340195.txt"
]
>>> uasort($data, function ($a, $b) {
... $pttrn = '#^[0-9]*--|\.txt$#';
... $ka = preg_replace($pttrn, '', $a);
... $kb = preg_replace($pttrn, '', $b);
... return $ka > $kb;
... })
>>> $data
=> [
3945 => "6358--338940.txt",
3949 => "6354--340195.txt",
3948 => "6354--345445.txt",
3947 => "6356--348265.txt",
3946 => "6357--348639.txt"
]