2014-11-25 84 views
0

我有一个包含文件排序数字PHP数组

[3945] => 6358--338940.txt 
    [3946] => 6357--348639.txt 
    [3947] => 6356--348265.txt 
    [3948] => 6354--345445.txt 
    [3949] => 6354--340195.txt 

我需要在使用后的数值下令数组列表的PHP数组$数据 - 文件名。 如何做到这一点?

感谢 问候

+1

使用[usort()](http://www.php.net/manual/en/function.usort.php)用自定义的回调 – 2014-11-25 09:19:28

+0

感谢,你能解释一下我的“与意义自定义回调“? – gr68 2014-11-25 09:21:05

+0

的文档可以。谷歌搜索可以。 – 2014-11-25 09:23:06

回答

0

如果你想要一个算法,良好的方式可以是:

下面是代码这样做:

<?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); 
?> 
0

你最好的选择是使用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" 
]